contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
getApproved
function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; }
/** * @dev See {IERC721-getApproved}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 6173, 6380 ] }
3,407
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
/** * @dev See {IERC721-setApprovalForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 6441, 6718 ] }
3,408
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
/** * @dev See {IERC721-isApprovedForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 6778, 6967 ] }
3,409
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); }
/** * @dev See {IERC721-transferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 7023, 7168 ] }
3,410
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 7228, 7388 ] }
3,411
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 7448, 7762 ] }
3,412
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_exists
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; }
/** * @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`), */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 7998, 8106 ] }
3,413
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_safeMint
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); }
/** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 8462, 9737 ] }
3,414
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_transfer
function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); }
/** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 9966, 11498 ] }
3,415
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_approve
function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
/** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 11601, 11776 ] }
3,416
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_setOwnersExplicit
function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; }
/** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 11927, 12772 ] }
3,417
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_checkOnERC721Received
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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } }
/** * @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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 13312, 14005 ] }
3,418
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_beforeTokenTransfers
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {}
/** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 14464, 14608 ] }
3,419
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_afterTokenTransfers
function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {}
/** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 14991, 15134 ] }
3,420
Nicks
Nicks.sol
0x4a261669208347bf4f47a565edd166c609b84797
Solidity
Nicks
contract Nicks { mapping (address => string) private nickOfOwner; mapping (string => address) private ownerOfNick; event Set (string indexed _nick, address indexed _owner); event Unset (string indexed _nick, address indexed _owner); constructor () public { contractOwner = msg.sender; } address public contractOwner; modifier onlyOwner() { require(contractOwner == msg.sender); _; } function nickOf (address _owner) public view returns (string _nick) { return nickOfOwner[_owner]; } function ownerOf (string _nick) public view returns (address _owner) { return ownerOfNick[_nick]; } function set (string _nick) public { require(bytes(_nick).length > 2); require(ownerOf(_nick) == address(0)); address owner = msg.sender; string storage oldNick = nickOfOwner[owner]; if (bytes(oldNick).length > 0) { emit Unset(oldNick, owner); delete ownerOfNick[oldNick]; } nickOfOwner[owner] = _nick; ownerOfNick[_nick] = owner; emit Set(_nick, owner); } function unset () public { require(bytes(nickOfOwner[msg.sender]).length > 0); address owner = msg.sender; string storage oldNick = nickOfOwner[owner]; emit Unset(oldNick, owner); delete ownerOfNick[oldNick]; delete nickOfOwner[owner]; } ///////////////////////////////// /// USEFUL FUNCTIONS /// //////////////////////////////// /* Fallback function to accept all ether sent directly to the contract */ function() payable public { } function withdrawEther() public onlyOwner { require(address(this).balance > 0); contractOwner.transfer(address(this).balance); } }
function() payable public { }
/* Fallback function to accept all ether sent directly to the contract */
Comment
v0.4.24+commit.e67f0147
bzzr://2954e0d91606a16f27fff5935b0d1c186a885a3050c4b37329da98747c200b9d
{ "func_code_index": [ 1558, 1600 ] }
3,421
WrapperDistributor721
WrapperDistributor.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperDistributor721
contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */
NatSpecMultiLine
WrapAndDistrib721WithMint
function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } }
/// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 528, 3016 ] }
3,422
WrapperDistributor721
WrapperDistributor.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperDistributor721
contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */
NatSpecMultiLine
WrapAndDistribEmpty
function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } }
/// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 3149, 5355 ] }
3,423
WrapperDistributor721
WrapperDistributor.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperDistributor721
contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */
NatSpecMultiLine
setDistributorState
function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; }
//////////////////////////////////////////////////////////////// ////////// Admins ////// ////////////////////////////////////////////////////////////////
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 5565, 5690 ] }
3,424
WrapperDistributor721
WrapperDistributor.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperDistributor721
contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */
NatSpecMultiLine
_baseURI
function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; }
////////////////////////////////////////////////////////////////
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 5761, 5902 ] }
3,425
WrapperDistributor721
WrapperDistributor.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperDistributor721
contract WrapperDistributor721 is WrapperWithERC20Collateral { using SafeERC20 for IERC20; using ERC165Checker for address; mapping(address => bool) public distributors; event GasLimit(uint256 wrappedAmountCount, address lastReceiver); constructor (address _erc20) WrapperWithERC20Collateral(_erc20) { distributors[msg.sender] = true; } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistrib721WithMint( address _original721, address[] memory _receivers, uint256[] memory _tokenIds, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); //require(_receivers.length <= 256, "Not more 256"); require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 1. Lits mint 721, but for gas save we will not do it for receiver // but wrapper contract as part of wrapp process IERC721Mintable(_original721).mint(address(this), _tokenIds[i]); // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _original721, _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.ERC721, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(_original721, _tokenIds[i], lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } /// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well function WrapAndDistribEmpty( address[] memory _receivers, ERC20Collateral[] memory _forDistrib, uint256 _unwrapAfter ) public payable { require(distributors[msg.sender], "Only for distributors"); require(_receivers.length <= 256, "Not more 256"); //require(_receivers.length == _tokenIds.length, "Not equal arrays"); // topup wrapper contract with erc20 that would be added in collateral for (uint8 i = 0; i < _forDistrib.length; i ++) { IERC20(_forDistrib[i].erc20Token).safeTransferFrom( msg.sender, address(this), _forDistrib[i].amount * _receivers.length ); } for (uint8 i = 0; i < _receivers.length; i ++) { // 2.Mint wrapped NFT for receiver and populate storage lastWrappedNFTId += 1; _mint(_receivers[i], lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( address(0), // _original721, 0, // _tokenIds[i], msg.value / _receivers.length, // native blockchain asset 0, // accumalated fee token _unwrapAfter, // timelock 0, //_transferFee, address(0), // _royaltyBeneficiary, 0, //_royaltyPercent, 0, //_unwraptFeeThreshold, address(0), //_transferFeeToken, AssetType.UNDEFINED, 0 ); // 3.Add erc20 collateral ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId]; for (uint8 j = 0; j < _forDistrib.length; j ++) { coll.push(ERC20Collateral({ erc20Token: _forDistrib[j].erc20Token, amount: _forDistrib[j].amount })); } emit Wrapped(address(0), 0, lastWrappedNFTId); // Safe Emergency exit if (gasleft() <= 1_000) { emit GasLimit(i + 1, _receivers[i]); return; } } } //////////////////////////////////////////////////////////////// ////////// Admins ////// //////////////////////////////////////////////////////////////// function setDistributorState(address _user, bool _state) external onlyOwner { distributors[_user] = _state; } //////////////////////////////////////////////////////////////// function _baseURI() internal view override(ERC721) returns (string memory) { return 'https://envelop.is/distribmetadata/'; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 with ability add ERC20 collateral */
NatSpecMultiLine
tokenURI
function tokenURI(uint256 _tokenId) public view override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return ERC721.tokenURI(_tokenId); } }
/** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 6063, 6407 ] }
3,426
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
setUGOVShareForTreasury
function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; }
// the bigger uGOVDivider is the less extra Ugov will be minted for the treasury
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2882, 3030 ] }
3,427
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
deposit
function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); }
// Deposit LP tokens to MasterChef for uGOV allocation.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3303, 3903 ] }
3,428
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
withdraw
function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); }
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3948, 4607 ] }
3,429
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
getRewards
function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; }
/// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4773, 5439 ] }
3,430
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
pendingUGOV
function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; }
// View function to see pending uGOVs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5496, 6224 ] }
3,431
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
getBondingShareInfo
function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; }
/** * @dev get the amount of shares and the reward debt of a bonding share . */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6320, 6506 ] }
3,432
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
totalShares
function totalShares() external view virtual returns (uint256) { return _totalShares; }
/** * @dev Total amount of shares . */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6561, 6664 ] }
3,433
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_updateUGOVMultiplier
function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } }
// UPDATE uGOV multiplier
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6696, 7448 ] }
3,434
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_updatePool
function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7517, 8473 ] }
3,435
BondingShareV2
contracts/MasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefV2
contract MasterChefV2 { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct BondingShareInfo { uint256 amount; // bonding rights. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } uint256 private _totalShares; // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; uint256 public uGOVDivider; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(uint256 => BondingShareInfo) private _bsInfo; event Deposit( address indexed user, uint256 amount, uint256 indexed bondingShareId ); event Withdraw( address indexed user, uint256 amount, uint256 indexed bondingShareId ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; _updatePool(); if (bs.amount > 0) { uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; _safeUGOVTransfer(to, pending); } bs.amount += _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares += _amount; emit Deposit(to, _amount, _bondingShareID); } // Withdraw LP tokens from MasterChef. function withdraw( address to, uint256 _amount, uint256 _bondingShareID ) external onlyBondingContract { BondingShareInfo storage bs = _bsInfo[_bondingShareID]; require(bs.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((bs.amount * pool.accuGOVPerShare) / 1e12) - bs.rewardDebt; // send UGOV to Bonding Share holder _safeUGOVTransfer(to, pending); bs.amount -= _amount; bs.rewardDebt = (bs.amount * pool.accuGOVPerShare) / 1e12; _totalShares -= _amount; emit Withdraw(to, _amount, _bondingShareID); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards(uint256 bondingShareID) external returns (uint256) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, bondingShareID ) == 1, "MS: caller is not owner" ); // calculate user reward BondingShareInfo storage user = _bsInfo[bondingShareID]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(uint256 bondingShareID) external view returns (uint256) { BondingShareInfo storage user = _bsInfo[bondingShareID]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } /** * @dev get the amount of shares and the reward debt of a bonding share . */ function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory) { return [_bsInfo[_id].amount, _bsInfo[_id].rewardDebt]; } /** * @dev Total amount of shares . */ function totalShares() external view virtual returns (uint256) { return _totalShares; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / uGOVDivider ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_safeUGOVTransfer
function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } }
// Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8587, 8951 ] }
3,436
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
deposit
function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); }
// Deposit LP tokens to MasterChef for uGOV allocation.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2820, 3358 ] }
3,437
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
withdraw
function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); }
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3403, 3954 ] }
3,438
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
getRewards
function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; }
/// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4120, 4503 ] }
3,439
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
pendingUGOV
function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; }
// View function to see pending uGOVs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4560, 5235 ] }
3,440
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_updateUGOVMultiplier
function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } }
// UPDATE uGOV multiplier
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5267, 6019 ] }
3,441
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_updatePool
function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6088, 7035 ] }
3,442
BondingShareV2
contracts/MasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChef
contract MasterChef { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many uAD-3CRV LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of uGOVs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accuGOVPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accuGOVPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { uint256 lastRewardBlock; // Last block number that uGOVs distribution occurs. uint256 accuGOVPerShare; // Accumulated uGOVs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // uGOV tokens created per block. uint256 public uGOVPerBlock = 1e18; // Bonus muliplier for early uGOV makers. uint256 public uGOVmultiplier = 1e18; uint256 public minPriceDiffToUpdateMultiplier = 1000000000000000; uint256 public lastPrice = 1 ether; // Info of each pool. PoolInfo public pool; // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } modifier onlyBondingContract() { require( msg.sender == manager.bondingContractAddress(), "MasterChef: not Bonding Contract" ); _; } constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); pool.lastRewardBlock = block.number; pool.accuGOVPerShare = 0; // uint256(1e12); _updateUGOVMultiplier(); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyTokenManager { uGOVPerBlock = _uGOVPerBlock; } function setMinPriceDiffToUpdateMultiplier( uint256 _minPriceDiffToUpdateMultiplier ) external onlyTokenManager { minPriceDiffToUpdateMultiplier = _minPriceDiffToUpdateMultiplier; } // Deposit LP tokens to MasterChef for uGOV allocation. function deposit(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; _updatePool(); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); } user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Deposit(sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external onlyBondingContract { UserInfo storage user = userInfo[sender]; require(user.amount >= _amount, "MC: amount too high"); _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; emit Withdraw(sender, _amount); } /// @dev get pending uGOV rewards from MasterChef. /// @return amount of pending rewards transfered to msg.sender /// @notice only send pending rewards function getRewards() external returns (uint256) { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = ((user.amount * pool.accuGOVPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.rewardDebt = (user.amount * pool.accuGOVPerShare) / 1e12; return pending; } // View function to see pending uGOVs on frontend. function pendingUGOV(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accuGOVPerShare = pool.accuGOVPerShare; uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; accuGOVPerShare = accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); } return (user.amount * accuGOVPerShare) / 1e12 - user.rewardDebt; } // UPDATE uGOV multiplier function _updateUGOVMultiplier() internal { // (1.05/(1+abs(1-TWAP_PRICE))) uint256 currentPrice = _getTwapPrice(); bool isPriceDiffEnough = false; // a minimum price variation is needed to update the multiplier if (currentPrice > lastPrice) { isPriceDiffEnough = currentPrice - lastPrice > minPriceDiffToUpdateMultiplier; } else { isPriceDiffEnough = lastPrice - currentPrice > minPriceDiffToUpdateMultiplier; } if (isPriceDiffEnough) { uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress()) .ugovMultiply(uGOVmultiplier, currentPrice); lastPrice = currentPrice; } } // Update reward variables of the given pool to be up-to-date. function _updatePool() internal { if (block.number <= pool.lastRewardBlock) { return; } _updateUGOVMultiplier(); uint256 lpSupply = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(); uint256 uGOVReward = (multiplier * uGOVPerBlock) / 1e18; IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), uGOVReward ); // mint another 20% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), uGOVReward / 5 ); pool.accuGOVPerShare = pool.accuGOVPerShare + ((uGOVReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } function _getMultiplier() internal view returns (uint256) { return (block.number - pool.lastRewardBlock) * uGOVmultiplier; } function _getTwapPrice() internal view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
_safeUGOVTransfer
function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } }
// Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7149, 7513 ] }
3,443
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
Oishifinance
function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); }
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 459, 803 ] }
3,444
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 991, 1112 ] }
3,445
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 1332, 1461 ] }
3,446
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 1805, 2082 ] }
3,447
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 2590, 2798 ] }
3,448
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 3329, 3687 ] }
3,449
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 3970, 4126 ] }
3,450
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 4481, 4798 ] }
3,451
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
function () public payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 4990, 5049 ] }
3,452
Oishifinance
Oishifinance.sol
0x10c1f65bebac506b87e527db48337856f2154c3c
Solidity
Oishifinance
contract Oishifinance is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Oishifinance() public { symbol = "OISHI"; name = "Oishi.finance"; decimals = 18; _totalSupply = 60000000000000000000000; balances[0x804A5936626d452f742DA4106E0A974Db68c96c0] = _totalSupply; Transfer(address(0), 0x804A5936626d452f742DA4106E0A974Db68c96c0, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://8f60df0dada6aa2682d7a597fdae5e873ed48983bc1f1a1aaec7c32f9948ac05
{ "func_code_index": [ 5282, 5471 ] }
3,453
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
TRCERC20
function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes }
/** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 1005, 1548 ] }
3,454
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
/** * Internal transfer, only can be called by this contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 1630, 2478 ] }
3,455
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
/** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 2682, 2839 ] }
3,456
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
/** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 3112, 3413 ] }
3,457
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 3675, 3905 ] }
3,458
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 4297, 4649 ] }
3,459
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; }
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 4817, 5196 ] }
3,460
TRCERC20
TRCERC20.sol
0x5b0fa053297f0ff35954531292d439a252f58919
Solidity
TRCERC20
contract TRCERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TRCERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; }
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://b18533ca01e56a7bb2990d41fedac9748fce77a25db28b165b294cf461312325
{ "func_code_index": [ 5452, 6068 ] }
3,461
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
wrap721
function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; }
/** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 3429, 6676 ] }
3,462
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
addNativeCollateral
function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; }
/** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 6829, 7064 ] }
3,463
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
unWrap721
function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); }
/** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 7316, 9481 ] }
3,464
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
chargeTransferFeeAndRoyalty
function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; }
/** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 9616, 10266 ] }
3,465
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
tokenURI
function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); }
/** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 10431, 10655 ] }
3,466
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
getTokenValue
function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); }
/** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 10870, 11066 ] }
3,467
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
getWrappedToken
function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; }
/** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 11240, 11369 ] }
3,468
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
setFee
function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); }
/////////////////////////////////////////////////////////////////////
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 11602, 11928 ] }
3,469
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } }
///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// /////////////////////////////////////////////////////////////////////
NatSpecSingleLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 12561, 13978 ] }
3,470
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
_chargeFee
function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; }
/** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 14175, 14528 ] }
3,471
WrapperDistributor721
WrapperBase.sol
0xdf6f4408497dfe745b116138b9338490366b2303
Solidity
WrapperBase
contract WrapperBase is ERC721Enumerable, Ownable, ReentrancyGuard, IFeeRoyaltyCharger { using SafeERC20 for IERC20; enum AssetType {UNDEFINED, ERC20, ERC721, ERC1155} struct NFT { address tokenContract; //Address of wrapping token contract uint256 tokenId; //Wrapping tokenId uint256 backedValue; //ETH uint256 backedTokens; //native project tokens uint256 unwrapAfter; //Freez date uint256 transferFee; //transferFee amount with decimals i.e. 20e18 address royaltyBeneficiary; //Royalty payments receiver uint256 royaltyPercent; //% from transferFee uint256 unwraptFeeThreshold;//unwrap possiple only after backedTokens achive this amount address transferFeeToken; //user can define transfer fee token contract from whitelist AssetType asset; //wrapped Asset type uint256 balance; //wrapping balance for erc 1155 } struct ListItem { bool enabledForCollateral; address transferFeeModel; bool disabledForWrap; } uint256 constant public MAX_ROYALTY_PERCENT = 50; uint256 constant public MAX_TIME_TO_UNWRAP = 365 days; uint256 constant public MAX_FEE_THRESHOLD_PERCENT = 1; //percent from project token totalSupply uint256 public protocolFee = 0; uint256 public chargeFeeAfter = type(uint256).max; uint256 public protocolFeeRaised; address public projectToken; address public protocolFeeToken; uint256 public lastWrappedNFTId; // Map from wrapped token id => NFT record mapping(uint256 => NFT) public wrappedTokens; //Private in Production // Map from conatrct address to enabled-as-collateral or blacklisted mapping(address => ListItem) public partnersTokenList; event Wrapped( address underlineContract, uint256 tokenId, uint256 indexed wrappedTokenId ); event UnWrapped( uint256 indexed wrappedId, address indexed owner, uint256 nativeCollateralAmount, uint256 feeAmount ); event NewFee(uint256 feeAmount, uint256 startDate); event NiftsyProtocolTransfer( uint256 indexed wrappedTokenId, address indexed royaltyBeneficiary, uint256 transferFee, uint256 royalty, address feeToken ); constructor(address _erc20) ERC721("ENVELOP Wrapped NFT Distributor", "wNFT") { require(_erc20 != address(0), "ProjectToken cant be zero value"); projectToken = _erc20; } /** * @dev DEPRICTAED method due * @dev Function for wrap existing ERC721 * * @param _underlineContract address of native NFT contract * @param _tokenId id of NFT that need to be wraped * @param _unwrapAfter Unix time value after that token can be unwrapped * @param _transferFee transferFee amount of projectToken with decimals i.e. 20e18 * @param _royaltyBeneficiary - address for royalty transfers * @param _royaltyPercent - integer 1..100, not more then MAX_ROYALTY_PERCENT * @param _unwraptFeeThreshold - token amounts in baccked fee for unwrap enable * @param _transferFeeToken - token address for fee and royalty settlemnet. By default * tech virtual project token * @return uint256 id of new wrapped token that represent old */ function wrap721( address _underlineContract, uint256 _tokenId, uint256 _unwrapAfter, uint256 _transferFee, address _royaltyBeneficiary, uint256 _royaltyPercent, uint256 _unwraptFeeThreshold, address _transferFeeToken ) external payable returns (uint256) { /////////////////Sanity checks//////////////////////// //0. Check blacklist for wrapping NFT require ( !partnersTokenList[_underlineContract].disabledForWrap, "This NFT is blacklisted for wrap" ); //1. ERC allowance // require( // IERC721(_underlineContract).getApproved(_tokenId) == address(this), // "Please call approve in your NFT contract" // ); //2. Logic around transfer fee if (_transferFee > 0) { if (_royaltyPercent > 0) { require(_royaltyPercent <= MAX_ROYALTY_PERCENT, "Royalty percent too big"); require(_royaltyBeneficiary != address(0), "Royalty to zero address"); } } else { require(_royaltyPercent == 0, "Royalty source is transferFee"); require(_royaltyBeneficiary == address(0), "No Royalty without transferFee"); require(_unwraptFeeThreshold == 0, "Cant set Threshold without transferFee"); } //3. MAX time to UNWRAP require( _unwrapAfter <= block.timestamp + MAX_TIME_TO_UNWRAP, "Too long Wrap" ); //4. For custom transfer fee token lets check MAX_FEE_THRESHOLD_PERCENT if (_transferFeeToken != address(0) && _transferFeeToken != projectToken) { require ( partnersTokenList[_transferFeeToken].enabledForCollateral, "This transferFee token is not enabled" ); require( _unwraptFeeThreshold < IERC20(_transferFeeToken).totalSupply() * MAX_FEE_THRESHOLD_PERCENT / 100, "Too much threshold" ); } ////////////////////////////////////////////////////// //Protocol fee can be not zero in the future // if (_getProtocolFeeAmount() > 0) { require( _chargeFee(msg.sender, _getProtocolFeeAmount()), "Cant charge protocol fee" ); protocolFeeRaised += _getProtocolFeeAmount(); } //////////////////////// /// WRAP LOGIC //// IERC721(_underlineContract).transferFrom(msg.sender, address(this), _tokenId); lastWrappedNFTId += 1; _mint(msg.sender, lastWrappedNFTId); wrappedTokens[lastWrappedNFTId] = NFT( _underlineContract, _tokenId, msg.value, 0, _unwrapAfter, _transferFee, _royaltyBeneficiary, _royaltyPercent, _unwraptFeeThreshold, _transferFeeToken, AssetType.ERC721, 0 ); emit Wrapped(_underlineContract, _tokenId, lastWrappedNFTId); return lastWrappedNFTId; } /** * @dev Function add native(eth, bnb) collateral to wrapped token * * @param _wrappedTokenId id of protocol token fo add */ function addNativeCollateral(uint256 _wrappedTokenId) external payable { require(ownerOf(_wrappedTokenId) != address(0)); NFT storage nft = wrappedTokens[_wrappedTokenId]; nft.backedValue += msg.value; } /** * @dev Function for unwrap protocol token. If wrapped NFT * has many erc20 collateral tokens it possible call this method * more than once, until unwrapped * * @param _tokenId id of protocol token to unwrapp */ function unWrap721(uint256 _tokenId) external nonReentrant { /////////////////////////////////////////////// //// Base Protocol checks /// /////////////////////////////////////////////// //1. Only token owner can UnWrap require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!'); //storoge did not work because there is no this var after delete NFT memory nft = wrappedTokens[_tokenId]; //2. Time lock check if (nft.unwrapAfter != 0) { require(nft.unwrapAfter <= block.timestamp, "Cant unwrap before day X"); } //3. Fee accumulated check if (nft.unwraptFeeThreshold > 0){ require(nft.backedTokens >= nft.unwraptFeeThreshold, "Cant unwrap due Fee Threshold"); } /////////////////////////////////////////////// /// Place for hook //// /////////////////////////////////////////////// if (!_beforeUnWrapHook(_tokenId)) { return; } /////////////////////////////////////////////// /// Main UnWrap Logic ////// /////////////////////////////////////////////// _burn(_tokenId); if (nft.asset == AssetType.ERC721) { IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId); } delete wrappedTokens[_tokenId]; //Return backed ether if (nft.backedValue > 0) { address payable toPayable = payable(msg.sender); toPayable.transfer(nft.backedValue); } //Return backed tokens if (nft.backedTokens > 0) { if (nft.transferFeeToken == address(0)) { IERC20(projectToken).transfer(msg.sender, nft.backedTokens); } else { IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens); } } emit UnWrapped( _tokenId, msg.sender, nft.backedValue, nft.backedTokens ); } /** * @dev Function is part of transferFeeModel interface * for charge fee in tech protokol Token * */ function chargeTransferFeeAndRoyalty( address from, address to, uint256 transferFee, uint256 royaltyPercent, address royaltyBeneficiary, address _transferFeeToken ) external override returns (uint256 feeIncrement) { require(msg.sender == address(this), "Wrapper only"); uint256 rAmount = royaltyPercent * transferFee / 100; ITechToken(projectToken).mint(address(this), transferFee - rAmount); if (rAmount > 0) { ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); } return transferFee - rAmount; } /** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */ function tokenURI(uint256 _tokenId) public view override virtual returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } /** * @dev Function returns tuple with accumulated amounts of * native chain collateral(eth, bnb,..) and transfer Fee * * @param _tokenId id of protocol token (new wrapped token) */ function getTokenValue(uint256 _tokenId) external view returns (uint256, uint256) { NFT storage nft = wrappedTokens[_tokenId]; return (nft.backedValue, nft.backedTokens); } /** * @dev Function returns structure with all data about * new protocol token * * @param _tokenId id of protocol token (new wrapped token) */ function getWrappedToken(uint256 _tokenId) external view returns (NFT memory) { return wrappedTokens[_tokenId]; } ///////////////////////////////////////////////////////////////////// // Admin functions // ///////////////////////////////////////////////////////////////////// function setFee(uint256 _fee, uint256 _startDate, address _protocolFeeToken) external onlyOwner { require(_protocolFeeToken != address(0), "No zero address"); protocolFee = _fee; chargeFeeAfter = _startDate; protocolFeeToken = _protocolFeeToken; emit NewFee(_fee, _startDate); } function editPartnersItem ( address _contract, bool _isCollateral, address _transferFeeModel, bool _isBlackListed ) external onlyOwner { partnersTokenList[_contract] = ListItem( _isCollateral, _transferFeeModel, _isBlackListed ); } ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///////////// Internals /////////////////////////////////////// ///////////////////////////////////////////////////////////////////// function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); //Not for mint and burn if (to != address(0) && from !=address(0)) { NFT storage nft = wrappedTokens[tokenId]; //Transfer fee charge if (nft.transferFee > 0) { address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel; // If there is no custom fee&royalty model then use // tech virtual protokol token if (feeCharger == address(0)) { feeCharger = address(this); } uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty( from, to, nft.transferFee, nft.royaltyPercent, nft.royaltyBeneficiary, nft.transferFeeToken ); nft.backedTokens += feeinc; emit NiftsyProtocolTransfer( tokenId, nft.royaltyBeneficiary, nft.transferFee, nft.transferFee - feeinc, nft.transferFeeToken ); } } } /** * @dev Function charge fee in project token * * @param _payer fee payer, must have non zero balance in project token * @param _amount fee amount for charge */ function _chargeFee(address _payer, uint256 _amount) internal returns(bool) { require( IERC20(protocolFeeToken).balanceOf(_payer) >= _amount, "insufficient protocol fee token balance for fee" ); IERC20(protocolFeeToken).transferFrom(_payer, address(this), _amount); return true; } /** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */ function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; } function _getProtocolFeeAmount() internal view returns (uint256) { if (block.timestamp >= chargeFeeAfter) { return protocolFee; } else { return 0; } } }
/** * @title ERC-721 Non-Fungible Token Wrapper * @dev For wrpap existing ERC721 and ERC1155(now only 721) */
NatSpecMultiLine
_beforeUnWrapHook
function _beforeUnWrapHook(uint256 _tokenId) internal virtual returns (bool){ return true; }
/** * @dev This hook may be overriden in inheritor contracts for extend * base functionality. * * @param _tokenId -wrapped token * * must returna true for success unwrapping enable */
NatSpecMultiLine
v0.8.11+commit.d7f03943
MIT
{ "func_code_index": [ 14755, 14863 ] }
3,472
OVM_L1ETHGateway
contracts/optimistic-ethereum/iOVM/bridge/tokens/iOVM_L2DepositedToken.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
iOVM_L2DepositedToken
interface iOVM_L2DepositedToken { /********** * Events * **********/ event WithdrawalInitiated( address indexed _from, address _to, uint256 _amount ); event DepositFinalized( address indexed _to, uint256 _amount ); /******************** * Public Functions * ********************/ function withdraw( uint _amount ) external; function withdrawTo( address _to, uint _amount ) external; /************************* * Cross-chain Functions * *************************/ function finalizeDeposit( address _to, uint _amount ) external; }
/** * @title iOVM_L2DepositedToken */
NatSpecMultiLine
withdraw
function withdraw( uint _amount ) external;
/******************** * Public Functions * ********************/
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 370, 437 ] }
3,473
OVM_L1ETHGateway
contracts/optimistic-ethereum/iOVM/bridge/tokens/iOVM_L2DepositedToken.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
iOVM_L2DepositedToken
interface iOVM_L2DepositedToken { /********** * Events * **********/ event WithdrawalInitiated( address indexed _from, address _to, uint256 _amount ); event DepositFinalized( address indexed _to, uint256 _amount ); /******************** * Public Functions * ********************/ function withdraw( uint _amount ) external; function withdrawTo( address _to, uint _amount ) external; /************************* * Cross-chain Functions * *************************/ function finalizeDeposit( address _to, uint _amount ) external; }
/** * @title iOVM_L2DepositedToken */
NatSpecMultiLine
finalizeDeposit
function finalizeDeposit( address _to, uint _amount ) external;
/************************* * Cross-chain Functions * *************************/
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 627, 722 ] }
3,474
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
// solhint-disable-next-line no-empty-blocks
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1373, 1406 ] }
3,475
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
uADPriceReset
function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); }
/// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1812, 2566 ] }
3,476
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
crvPriceReset
function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); }
/// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2980, 3742 ] }
3,477
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
addProtocolToken
function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); }
/// Collectable Dust
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3769, 3922 ] }
3,478
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
deposit
function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); }
/// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5806, 6865 ] }
3,479
BondingShareV2
contracts/Bonding.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
Bonding
contract Bonding is CollectableDust { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals ISablier public sablier; uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public redeemStreamTime = 86400; // 1 day in seconds uint256 public blockCountInAWeek = 45361; uint256 public blockRonding = 100; uint256 public uGOVPerBlock = 1; event MaxBondingPriceUpdated(uint256 _maxBondingPrice); event SablierUpdated(address _sablier); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event RedeemStreamTimeUpdated(uint256 _redeemStreamTime); event BlockRondingUpdated(uint256 _blockRonding); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event UGOVPerBlockUpdated(uint256 _uGOVPerBlock); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "Caller is not a bonding manager" ); _; } constructor(address _manager, address _sablier) CollectableDust() { manager = UbiquityAlgorithmicDollarManager(_manager); sablier = ISablier(_sablier); } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 0, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.dollarTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.dollarTokenAddress()).balanceOf(address(this)) ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // safe approve IERC20(manager.stableSwapMetaPoolAddress()).safeApprove( address(this), amount ); // remove one coin uint256 expected = (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100; // update twap metaPool.remove_liquidity_one_coin(amount, 1, expected); ITWAPOracle(manager.twapOracleAddress()).update(); IERC20(manager.curve3PoolTokenAddress()).safeTransfer( manager.treasuryAddress(), IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this)) ); } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setSablier(address _sablier) external onlyBondingManager { sablier = ISablier(_sablier); emit SablierUpdated(_sablier); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setRedeemStreamTime(uint256 _redeemStreamTime) external onlyBondingManager { redeemStreamTime = _redeemStreamTime; emit RedeemStreamTimeUpdated(_redeemStreamTime); } function setBlockRonding(uint256 _blockRonding) external onlyBondingManager { blockRonding = _blockRonding; emit BlockRondingUpdated(_blockRonding); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } function setUGOVPerBlock(uint256 _uGOVPerBlock) external onlyBondingManager { uGOVPerBlock = _uGOVPerBlock; emit UGOVPerBlockUpdated(_uGOVPerBlock); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) public returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); _updateOracle(); IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) // id = n - n % blockRonding // blockRonding = 100 => 2 ending zeros uint256 n = block.number + _weeks * blockCountInAWeek; _id = n - (n % blockRonding); _mint(_sharesAmount, _id); // set masterchef for uGOV rewards IMasterChef(manager.masterChefAddress()).deposit( _sharesAmount, msg.sender ); } /// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalLP = IERC20(manager.stableSwapMetaPoolAddress()).balanceOf( address(this) ); uint256 totalShares = IERC1155Ubiquity(manager.bondingShareAddress()) .totalSupply(); priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( totalLP, totalShares, ONE ); } function currentTokenPrice() public view returns (uint256) { return ITWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } function _mint(uint256 _sharesAmount, uint256 _id) internal { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); IERC1155Ubiquity(manager.bondingShareAddress()).mint( msg.sender, _id, _sharesAmount, data ); } function _updateOracle() internal { ITWAPOracle(manager.twapOracleAddress()).update(); } }
withdraw
function withdraw(uint256 _sharesAmount, uint256 _id) public { require( block.number > _id, "Bonding: Redeem not allowed before bonding time" ); require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) >= _sharesAmount, "Bonding: caller does not have enough shares" ); _updateOracle(); // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE burning the shares IMasterChef(manager.masterChefAddress()).withdraw( _sharesAmount, msg.sender ); uint256 _currentShareValue = currentShareValue(); IERC1155Ubiquity(manager.bondingShareAddress()).burn( msg.sender, _id, _sharesAmount ); // if (redeemStreamTime == 0) { IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer( msg.sender, IUbiquityFormulas(manager.formulasAddress()).redeemBonds( _sharesAmount, _currentShareValue, ONE ) ); }
/// @dev withdraw an amount of uAD-3CRV LP tokens /// @param _sharesAmount of bonding shares of type _id to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7123, 8344 ] }
3,480
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 261, 314 ] }
3,481
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 637, 813 ] }
3,482
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 268, 659 ] }
3,483
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 865, 977 ] }
3,484
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 401, 853 ] }
3,485
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 1485, 1675 ] }
3,486
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 1999, 2130 ] }
3,487
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 2596, 2860 ] }
3,488
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 3331, 3741 ] }
3,489
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
MintableAndBurnableToken
contract MintableAndBurnableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
mint
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
/** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 498, 769 ] }
3,490
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
MintableAndBurnableToken
contract MintableAndBurnableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
finishMinting
function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; }
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 886, 1028 ] }
3,491
QuasacoinTransferToken
QuasacoinTransferToken.sol
0xd543136385b966ea41fc2cc9820dff390bac636a
Solidity
MintableAndBurnableToken
contract MintableAndBurnableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
burn
function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); }
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a2f448998ed6764cdcbdf364d0d6e59f2a19872f35133b3319abed0ec1388c73
{ "func_code_index": [ 1200, 1640 ] }
3,492
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 92, 152 ] }
3,493
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 233, 306 ] }
3,494
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 524, 606 ] }
3,495
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 879, 967 ] }
3,496
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1618, 1697 ] }
3,497
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 2002, 2104 ] }
3,498
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
tryAdd
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } }
/** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 157, 384 ] }
3,499
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
trySub
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } }
/** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 528, 727 ] }
3,500
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
tryMul
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } }
/** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 873, 1381 ] }
3,501
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
tryDiv
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } }
/** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1528, 1728 ] }
3,502
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
tryMod
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } }
/** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1885, 2085 ] }
3,503
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 2318, 2421 ] }
3,504
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 2690, 2793 ] }
3,505
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 3038, 3141 ] }
3,506