file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0xFB15127f6464fcBB82b05Dc4b772283236C65167/sources/LexSecurityToken.sol
prev. withdrawableDividendOf View the amount of funds that an address can withdraw. _owner The address of a token holder. return The amount funds that `_owner` can withdraw./
function withdrawableFundsOf(address _owner) public view returns(uint256) { return accumulativeFundsOf(_owner).sub(withdrawnFunds[_owner]); }
3,647,131
./full_match/43113/0x79D0b125CEA315aAB0Bb1BC2322287D3EBB88E47/sources/home/pedro/Documents/projects/avalabs/party-swap/party-swap-core/contracts/PartyPair.sol
update reserves and, on the first call per block, price accumulators never overflows, and + overflow is desired
function _update( uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1 ) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Party: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); }
7,113,787
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./mixins/OZ/ERC721Upgradeable.sol"; import "./mixins/roles/MomentsAdminRole.sol"; import "./mixins/MarketNode.sol"; import "./mixins/NFT721Metadata.sol"; import "./mixins/NFT721Mint.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Moments NFTs implemented using the ERC-721 standard. * @dev This top level file holds no data directly to ease future upgrades. */ contract MOMENTSNFT is ERC165StorageUpgradeable, AccessControlUpgradeable, MomentsAdminRole, ERC721Upgradeable, NFT721Metadata, NFT721Mint, OwnableUpgradeable { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ function initialize( address market, address admin, string memory name, string memory symbol, string memory _baseURI ) public initializer { MarketNode._initializeMarketNode(market); MomentsAdminRole._initializeAdminRole(admin); ERC721Upgradeable.__ERC721_init(name, symbol); NFT721Mint._initializeNFT721Mint(); _updateBaseURI(_baseURI); __Ownable_init(); } /** * @notice Allows a Moments admin to update NFT config variables. * @dev This must be called right after the initial call to `initialize`. */ function adminUpdateConfig(string memory _baseURI, address market) external onlyMomentsAdmin { _updateBaseURI(_baseURI); _updateMarket(market); } /** * @notice Overrided before transfer to restrict multiple perk transfer . */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable) { if (perkTransfer[tokenId] >= 1 && to != getMarket()) { perkTransfer[tokenId] = ++perkTransfer[tokenId]; } require( perkTransfer[tokenId] <= 2 || to == address(0), "Perk transfer limit reached" ); super._beforeTokenTransfer(from, to, tokenId); } /** * @notice Allows a Moments admin to update perk transfer count. */ function perkTransferCount(uint256 tokenId) external onlyMomentsAdmin { require(perkTransfer[tokenId] > 1, "No change required"); perkTransfer[tokenId] = 1; } /** * @dev Explicit override to address compile errors. */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC165StorageUpgradeable, AccessControlUpgradeable, NFT721Metadata, NFT721Mint ) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev This is a no-op, just an explicit override to address compile errors due to inheritance. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Metadata, NFT721Mint) { super._burn(tokenId); } } // SPDX-License-Identifier: MIT // solhint-disable /** * Copied from the OpenZeppelin repository in order to make `_tokenURIs` internal instead of private. */ pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableMapUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165StorageUpgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @notice Wraps the default admin role from OpenZeppelin's AccessControl for easy integration. */ abstract contract MomentsAdminRole is Initializable, AccessControlUpgradeable { function _initializeAdminRole(address admin) internal initializer { AccessControlUpgradeable.__AccessControl_init(); // Grant the role to a specified account _setupRole(DEFAULT_ADMIN_ROLE, admin); } modifier onlyMomentsAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "AdminRole: caller does not have the Admin role" ); _; } function isAdmin(address account) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account); } /** * @dev onlyAdmin is enforced by `grantRole`. */ function grantAdmin(address account) external { grantRole(DEFAULT_ADMIN_ROLE, account); } /** * @dev onlyAdmin is enforced by `revokeRole`. */ function revokeAdmin(address account) external { revokeRole(DEFAULT_ADMIN_ROLE, account); } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Moments market contract. */ abstract contract MarketNode is Initializable { using AddressUpgradeable for address; address private market; /** * @dev Called once after the initial deployment to set the market address. */ function _initializeMarketNode(address _market) internal initializer { require(_market.isContract(), "Market Node: Address is not a contract"); market = _market; } /** * @notice Returns the address of the market. */ function getMarket() public view returns (address) { return market; } /** * @notice Updates the address of the market. */ function _updateMarket(address _market) internal { require(_market.isContract(), "Market Node: Address is not a contract"); market = _market; } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./OZ/ERC721Upgradeable.sol"; import "./roles/MomentsAdminRole.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; /** * @notice A mixin to extend the OpenZeppelin metadata implementation. */ abstract contract NFT721Metadata is ERC165StorageUpgradeable, AccessControlUpgradeable, MomentsAdminRole, ERC721Upgradeable { using StringsUpgradeable for uint256; /** * @dev Stores token path to avoid duplication in token uri. */ mapping(string => bool) private tokenUriMinted; event BaseURIUpdated(string baseURI); modifier onlyCreatorAndOwner(uint256 tokenId) { require( ownerOf(tokenId) == msg.sender || isAdmin(msg.sender), "NFT721: Caller does not own the NFT or not the admin" ); _; } /** * @notice Checks if the nft is already minted. */ function getMintedTokenUri(string memory tokenUri) external view returns (bool) { return tokenUriMinted[tokenUri]; } /** * @notice Sets the token path. */ function _setTokenUriPath(uint256 tokenId, string memory tokenUri) internal { require( bytes(tokenUri).length > 0, "NFT721Metadata: Invalid token path" ); require( !tokenUriMinted[tokenUri], "NFT721Metadata: NFT was already minted" ); tokenUriMinted[tokenUri] = true; _setTokenURI(tokenId, tokenUri); } /** * @notice Updates base uri. */ function _updateBaseURI(string memory _baseURI) internal { _setBaseURI(_baseURI); emit BaseURIUpdated(_baseURI); } /** * @notice Allows the creator or owner to burn if they currently own the NFT. */ function burn(uint256 tokenId) external onlyCreatorAndOwner(tokenId) { _burn(tokenId); } /** * @dev Remove the record when burned. */ function _burn(uint256 tokenId) internal virtual override { delete tokenUriMinted[_tokenURIs[tokenId]]; super._burn(tokenId); } /** * @dev Explicit override to address compile errors. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165StorageUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.4; import "./OZ/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./MarketNode.sol"; import "./NFT721Metadata.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; /** * @notice Allows creators to mint NFTs. */ abstract contract NFT721Mint is ERC165StorageUpgradeable, AccessControlUpgradeable, ERC721Upgradeable, MarketNode, NFT721Metadata { using AddressUpgradeable for address; uint256 private nextTokenId; mapping(uint256 => uint256) public perkTransfer; event Minted( address indexed creator, uint256 indexed tokenId, string tokenPath ); /** * @notice Gets the tokenId of the next NFT minted. */ function getNextTokenId() public view returns (uint256) { return nextTokenId; } /** * @dev Called once after the initial deployment to set the initial tokenId. */ function _initializeNFT721Mint() internal initializer { // Use ID 1 for the first NFT tokenId nextTokenId = 1; } /** * @notice Allows creators to mint an asset. */ function mint(string memory tokenPath) external returns (uint256 tokenId) { tokenId = nextTokenId++; _mint(msg.sender, tokenId); _setTokenUriPath(tokenId, tokenPath); setApprovalForAll(getMarket(), true); emit Minted(msg.sender, tokenId, tokenPath); } /** * @notice Allows creators to mint perk. */ function mintPerk(string memory tokenPath) external returns (uint256 tokenId) { tokenId = nextTokenId++; _mint(msg.sender, tokenId); _setTokenUriPath(tokenId, tokenPath); setApprovalForAll(getMarket(), true); perkTransfer[tokenId] = 1; emit Minted(msg.sender, tokenId, tokenPath); } /** * @dev Explicit override to address compile errors. */ function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Metadata) { if (perkTransfer[tokenId] > 0) { delete perkTransfer[tokenId]; } super._burn(tokenId); } /** * @dev Explicit override to address compile errors. */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC165StorageUpgradeable, AccessControlUpgradeable, NFT721Metadata ) returns (bool) { return super.supportsInterface(interfaceId); } uint256[1000] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable { function __ERC165Storage_init() internal initializer { __ERC165_init_unchained(); __ERC165Storage_init_unchained(); } function __ERC165Storage_init_unchained() internal initializer { } /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @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. */ library SafeMathUpgradeable { /** * @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. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./EnumerableSetUpgradeable.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSetUpgradeable.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; }
Checks if the nft is already minted./
function getMintedTokenUri(string memory tokenUri) external view returns (bool) { return tokenUriMinted[tokenUri]; }
12,250,139
pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IPancakeRouter02.sol"; import "./interfaces/IWETH.sol"; contract FeeReceiver is Pausable, Ownable { using SafeMath for uint256; event BuybackRateUpdated(uint256 newBuybackRate); event RevenueReceiverUpdated(address newRevenueReceiver); event RouterWhitelistUpdated(address router, bool status); event BuybackExecuted(uint256 amountBuyback, uint256 amountRevenue); address internal constant ZERO_ADDRESS = address(0); uint256 public constant FEE_DENOMINATOR = 10000; IPancakeRouter02 public pancakeRouter; address payable public revenueReceiver; uint256 public buybackRate; address public SYA; address public WETH; mapping(address => bool) public routerWhitelist; constructor( IPancakeRouter02 _pancakeRouterV2, address _SYA, address _WETH, address payable _revenueReceiver, uint256 _buybackRate ) public { pancakeRouter = _pancakeRouterV2; SYA = _SYA; WETH = _WETH; revenueReceiver = _revenueReceiver; buybackRate = _buybackRate; routerWhitelist[address(pancakeRouter)] = true; } /// @dev executes the buyback, buys SYA on pancake & sends revenue to the revenueReceiver by the defined rate. function executeBuyback() external whenNotPaused { require(address(this).balance > 0, "FeeReceiver: No balance for buyback"); address[] memory path = new address[](2); path[0] = WETH; path[1] = SYA; uint256 balance = address(this).balance; uint256 amountBuyback = balance.mul(buybackRate).div(FEE_DENOMINATOR); uint256 amountRevenue = balance.sub(amountBuyback); pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountBuyback}( 0, path, ZERO_ADDRESS, block.timestamp ); TransferHelper.safeTransferETH(revenueReceiver, amountRevenue); emit BuybackExecuted(amountBuyback, amountRevenue); } /// @dev converts collected tokens from fees to ETH for executing buybacks function convertToETH( address _router, IERC20 _token, bool _fee ) public whenNotPaused { require(routerWhitelist[_router], "FeeReceiver: Router not whitelisted"); address[] memory path = new address[](2); path[0] = address(_token); path[1] = WETH; uint256 balance = _token.balanceOf(address(this)); TransferHelper.safeApprove(address(_token), address(pancakeRouter), balance); if (_fee) { IPancakeRouter02(_router).swapExactTokensForETHSupportingFeeOnTransferTokens( balance, 0, path, address(this), block.timestamp ); } else { IPancakeRouter02(_router).swapExactTokensForETH(balance, 0, path, address(this), block.timestamp); } } /// @dev converts WETH to ETH function unwrapWETH() public whenNotPaused { uint256 balance = IWETH(WETH).balanceOf(address(this)); require(balance > 0, "FeeReceiver: Nothing to unwrap"); IWETH(WETH).withdraw(balance); } /// @dev lets the owner update update the router whitelist function updateRouterWhiteliste(address _router, bool _status) external onlyOwner { routerWhitelist[_router] = _status; emit RouterWhitelistUpdated(_router, _status); } /// @dev lets the owner update the buyback rate function updateBuybackRate(uint256 _newBuybackRate) external onlyOwner { buybackRate = _newBuybackRate; emit BuybackRateUpdated(_newBuybackRate); } /// @dev lets the owner update the revenue receiver address function updateRevenueReceiver(address payable _newRevenueReceiver) external onlyOwner { revenueReceiver = _newRevenueReceiver; emit RevenueReceiverUpdated(_newRevenueReceiver); } /// @dev lets the owner withdraw ETH from the contract function withdrawETH(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @dev lets the owner withdraw any ERC20 Token from the contract function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /// @dev allows to receive ETH on this contract receive() external payable {} /// @dev lets the owner pause the contract function pause() external onlyOwner { _pause(); } /// @dev lets the owner unpause the contract function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity =0.6.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } } pragma solidity >=0.6.2; import "./IPancakeRouter01.sol"; interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.2; interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } pragma solidity =0.6.6; import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./libraries/PancakeLibrary.sol"; import "./interfaces/IReferralRegistry.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IZerox.sol"; contract FloozRouter is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using LibBytesV06 for bytes; event SwapFeeUpdated(uint16 swapFee); event ReferralRegistryUpdated(address referralRegistry); event ReferralRewardRateUpdated(uint16 referralRewardRate); event ReferralsActivatedUpdated(bool activated); event FeeReceiverUpdated(address payable feeReceiver); event BalanceThresholdUpdated(uint256 balanceThreshold); event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate); event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount); event ForkUpdated(address factory); // Denominator of fee uint256 public constant FEE_DENOMINATOR = 10000; // Numerator of fee uint16 public swapFee; // address of WETH address public immutable WETH; // address of zeroEx proxy contract to forward swaps address payable public immutable zeroEx; // address of 1inch contract to forward swaps address payable public immutable oneInch; // address of referral registry that stores referral anchors IReferralRegistry public referralRegistry; // address of SYA token IERC20 public saveYourAssetsToken; // balance threshold of SYA tokens which actives feeless swapping uint256 public balanceThreshold; // address that receives protocol fees address payable public feeReceiver; // percentage of fees that will be paid as rewards uint16 public referralRewardRate; // stores if the referral system is turned on or off bool public referralsActivated; // stores individual referral rates mapping(address => uint16) public customReferralRewardRate; // stores uniswap forks status, index is the factory address mapping(address => bool) public forkActivated; // stores uniswap forks initCodes, index is the factory address mapping(address => bytes) public forkInitCode; /// @dev construct this contract /// @param _WETH address of WETH. /// @param _swapFee nominator for swapFee. Denominator = 10000 /// @param _referralRewardRate percentage of swapFee that are paid out as rewards /// @param _feeReceiver address that receives protocol fees /// @param _balanceThreshold balance threshold of SYA tokens which actives feeless swapping /// @param _saveYourAssetsToken address of SYA token /// @param _referralRegistry address of referral registry that stores referral anchors /// @param _zeroEx address of zeroX proxy contract to forward swaps /// @param _oneInch address of 1inch contract to forward swaps constructor( address _WETH, uint16 _swapFee, uint16 _referralRewardRate, address payable _feeReceiver, uint256 _balanceThreshold, IERC20 _saveYourAssetsToken, IReferralRegistry _referralRegistry, address payable _zeroEx, address payable _oneInch ) public { WETH = _WETH; swapFee = _swapFee; referralRewardRate = _referralRewardRate; feeReceiver = _feeReceiver; saveYourAssetsToken = _saveYourAssetsToken; balanceThreshold = _balanceThreshold; referralRegistry = _referralRegistry; zeroEx = _zeroEx; oneInch = _oneInch; referralsActivated = true; } /// @dev execute swap directly on Uniswap/Pancake & simular forks /// @param fork fork used to execute swap /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactETHForTokens( address fork, uint256 amountOutMin, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); amounts = _getAmountsOut(fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0])); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount of tokensIn /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactTokensForETHSupportingFeeOnTransferTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amountIn); _swapSupportingFeeOnTransferTokens(fork, path, address(this)); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountOut, referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE"); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactTokensForTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountIn, referee, false ); amounts = _getAmountsOut(fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapExactTokensForETH( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); amounts = _getAmountsOut(fork, amountIn, path); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amounts[amounts.length - 1], referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected amount of tokens out /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapETHForExactTokens( address fork, uint256 amountOut, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); amounts = _getAmountsIn(fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true); require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), amounts[0])); _swap(fork, amounts, path, msg.sender); // refund dust eth, if any if (msg.value > amounts[0].add(feeAmount).add(referralReward)) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward)); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactTokensForTokensSupportingFeeOnTransferTokens( address fork, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) { referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( amountIn, referee, false ); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), swapAmount); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapTokensForExactTokens( address fork, uint256 amountOut, uint256 amountInMax, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { referee = _getReferee(referee); amounts = _getAmountsIn(fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amounts[0], referee, true); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none /// @return amounts function swapTokensForExactETH( address fork, uint256 amountOut, uint256 amountInMax, address[] calldata path, address referee ) external whenNotPaused isValidFork(fork) isValidReferee(referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards(amountOut, referee, true); amounts = _getAmountsIn(fork, amountOut.add(feeAmount).add(referralReward), path); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(fork, path[0], path[1]), amounts[0]); _swap(fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountOut); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param fork fork used to execute swap /// @param amountOutMin minimum expected tokens to receive /// @param path Sell path. /// @param referee address of referee for msg.sender, 0x adress if none function swapExactETHForTokensSupportingFeeOnTransferTokens( address fork, uint256 amountOutMin, address[] calldata path, address referee ) external payable whenNotPaused isValidFork(fork) isValidReferee(referee) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); referee = _getReferee(referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); IWETH(WETH).deposit{value: swapAmount}(); assert(IWETH(WETH).transfer(_pairFor(fork, path[0], path[1]), swapAmount)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev returns the referee for a given address, if new, registers referee /// @param referee the address of the referee for msg.sender /// @return referee address from referral registry function _getReferee(address referee) internal returns (address) { address sender = msg.sender; if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) { referralRegistry.createReferralAnchor(sender, referee); } return referralRegistry.getUserReferee(sender); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( address fork, uint256[] memory amounts, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address fork, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(_pairFor(fork, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /// @dev Executes a swap on 0x API /// @param data calldata expected by data field on 0x API (https://0x.org/docs/api#response-1) /// @param tokenOut the address of currency to sell – 0x address for ETH /// @param tokenIn the address of currency to buy – 0x address for ETH /// @param referee address of referee for msg.sender, 0x adress if none function executeZeroExSwap( bytes calldata data, address tokenOut, address tokenIn, address referee ) external payable nonReentrant whenNotPaused isValidReferee(referee) { referee = _getReferee(referee); bytes4 selector = data.readBytes4(0); address impl = IZerox(zeroEx).getFunctionImplementation(selector); require(impl != address(0), "FloozRouter: NO_IMPLEMENTATION"); bool isAboveThreshold = userAboveBalanceThreshold(msg.sender); // skip fees & rewards for god mode users if (isAboveThreshold) { (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); } else { // if ETH in execute trade as router & distribute funds & fees if (msg.value > 0) { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( msg.value, referee, false ); (bool success, ) = impl.call{value: swapAmount}(data); require(success, "FloozRouter: REVERTED"); TransferHelper.safeTransfer(tokenIn, msg.sender, IERC20(tokenIn).balanceOf(address(this))); _withdrawFeesAndRewards(address(0), tokenIn, referee, feeAmount, referralReward); } else { uint256 balanceBefore = IERC20(tokenOut).balanceOf(msg.sender); (bool success, ) = impl.delegatecall(data); require(success, "FloozRouter: REVERTED"); uint256 balanceAfter = IERC20(tokenOut).balanceOf(msg.sender); require(balanceBefore > balanceAfter, "INVALID_TOKEN"); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( balanceBefore.sub(balanceAfter), referee, true ); _withdrawFeesAndRewards(tokenOut, tokenIn, referee, feeAmount, referralReward); } } } /// @dev calculates swap, fee & reward amounts /// @param amount total amount of tokens /// @param referee the address of the referee for msg.sender function _calculateFeesAndRewards( uint256 amount, address referee, bool additiveFee ) internal view returns ( uint256 swapAmount, uint256 feeAmount, uint256 referralReward ) { // no fees for users above threshold if (userAboveBalanceThreshold(msg.sender)) { swapAmount = amount; } else { if (additiveFee) { swapAmount = amount; feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount); } else { feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR); swapAmount = amount.sub(feeAmount); } // calculate referral rates, if referee is not 0x if (referee != address(0) && referralsActivated) { uint16 referralRate = customReferralRewardRate[referee] > 0 ? customReferralRewardRate[referee] : referralRewardRate; referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR); feeAmount = feeAmount.sub(referralReward); } else { referralReward = 0; } } } /// @dev lets the admin update an Uniswap style fork function updateFork( address _factory, bytes calldata _initCode, bool _activated ) external onlyOwner { forkActivated[_factory] = _activated; forkInitCode[_factory] = _initCode; emit ForkUpdated(_factory); } /// @dev returns if a users is above the SYA threshold and can swap without fees function userAboveBalanceThreshold(address _account) public view returns (bool) { return saveYourAssetsToken.balanceOf(_account) >= balanceThreshold; } /// @dev returns the fee nominator for a given user function getUserFee(address user) public view returns (uint256) { saveYourAssetsToken.balanceOf(user) >= balanceThreshold ? 0 : swapFee; } /// @dev lets the admin update the swapFee nominator function updateSwapFee(uint16 newSwapFee) external onlyOwner { swapFee = newSwapFee; emit SwapFeeUpdated(newSwapFee); } /// @dev lets the admin update the referral reward rate function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner { require(newReferralRewardRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); referralRewardRate = newReferralRewardRate; emit ReferralRewardRateUpdated(newReferralRewardRate); } /// @dev lets the admin update which address receives the protocol fees function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner { feeReceiver = newFeeReceiver; emit FeeReceiverUpdated(newFeeReceiver); } /// @dev lets the admin update the SYA balance threshold, which activates feeless trading for users function updateBalanceThreshold(uint256 newBalanceThreshold) external onlyOwner { balanceThreshold = newBalanceThreshold; emit BalanceThresholdUpdated(balanceThreshold); } /// @dev lets the admin update the status of the referral system function updateReferralsActivated(bool newReferralsActivated) external onlyOwner { referralsActivated = newReferralsActivated; emit ReferralsActivatedUpdated(newReferralsActivated); } /// @dev lets the admin set a new referral registry function updateReferralRegistry(address newReferralRegistry) external onlyOwner { referralRegistry = IReferralRegistry(newReferralRegistry); emit ReferralRegistryUpdated(newReferralRegistry); } /// @dev lets the admin set a custom referral rate function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) { require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); customReferralRewardRate[account] = referralRate; emit CustomReferralRewardRateUpdated(account, referralRate); } /// @dev returns the referee for a given user – 0x address if none function getUserReferee(address user) external view returns (address) { return referralRegistry.getUserReferee(user); } /// @dev returns if the given user has been referred or not function hasUserReferee(address user) external view returns (bool) { return referralRegistry.hasUserReferee(user); } /// @dev lets the admin withdraw ETH from the contract. function withdrawETH(address payable to, uint256 amount) external onlyOwner { TransferHelper.safeTransferETH(to, amount); } /// @dev lets the admin withdraw ERC20s from the contract. function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { TransferHelper.safeTransfer(token, to, amount); } /// @dev distributes fees & referral rewards to users function _withdrawFeesAndRewards( address tokenReward, address tokenOut, address referee, uint256 feeAmount, uint256 referralReward ) internal { if (tokenReward == address(0)) { TransferHelper.safeTransferETH(feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferETH(referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } else { TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } } /// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul((9980)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } /// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(10000); uint256 denominator = reserveOut.sub(amountOut).mul(9980); amountIn = (numerator / denominator).add(1); } /// @dev performs chained getAmountOut calculations on any number of pairs function _getAmountsOut( address fork, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]); amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut); } } /// @dev performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } /// @dev fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @dev calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { (address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), forkInitCode[factory] // init code hash ) ) ) ); } /// @dev lets the admin pause this contract function pause() external onlyOwner { _pause(); } /// @dev lets the admin unpause this contract function unpause() external onlyOwner { _unpause(); } /// @dev allows to receive ETH on the contract receive() external payable {} modifier isValidFork(address factory) { require(forkActivated[factory], "FloozRouter: INVALID_FACTORY"); _; } modifier isValidReferee(address referee) { require(msg.sender != referee, "FloozRouter: SELF_REFERRAL"); _; } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; import "./errors/LibBytesRichErrorsV06.sol"; import "./errors/LibRichErrorsV06.sol"; library LibBytesV06 { using LibBytesV06 for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// When `from == 0`, the original array will match the slice. /// In other cases its state will be corrupted. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError( LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity =0.6.6; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IPancakePair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library PancakeLibrary { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "PancakeLibrary: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "PancakeLibrary: ZERO_ADDRESS"); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "PancakeLibrary: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "PancakeLibrary: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } } pragma solidity >=0.5.0; interface IReferralRegistry { function getUserReferee(address _user) external view returns (address); function hasUserReferee(address _user) external view returns (bool); function createReferralAnchor(address _user, address _referee) external; } pragma solidity ^0.6.5; interface IZerox { function getFunctionImplementation(bytes4 selector) external returns (address payable); } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibBytesRichErrorsV06 { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; library LibRichErrorsV06 { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError(string memory message) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } pragma solidity =0.6.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./libraries/TransferHelper.sol"; import "./libraries/PancakeLibrary.sol"; import "./interfaces/IReferralRegistry.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IZerox.sol"; contract FloozMultichainRouter is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; event SwapFeeUpdated(uint16 swapFee); event ReferralRegistryUpdated(address referralRegistry); event ReferralRewardRateUpdated(uint16 referralRewardRate); event ReferralsActivatedUpdated(bool activated); event FeeReceiverUpdated(address payable feeReceiver); event CustomReferralRewardRateUpdated(address indexed account, uint16 referralRate); event ReferralRewardPaid(address from, address indexed to, address tokenOut, address tokenReward, uint256 amount); event ForkCreated(address factory); event ForkUpdated(address factory); struct SwapData { address fork; address referee; bool fee; } struct ExternalSwapData { bytes data; address fromToken; address toToken; uint256 amountFrom; address referee; uint256 minOut; bool fee; } // Denominator of fee uint256 public constant FEE_DENOMINATOR = 10000; // Numerator of fee uint16 public swapFee; // address of WETH address public immutable WETH; // address of zeroEx proxy contract to forward swaps address payable public immutable zeroEx; // address of 1inch contract to forward swaps address payable public immutable oneInch; // address of referral registry that stores referral anchors IReferralRegistry public referralRegistry; // address that receives protocol fees address payable public feeReceiver; // percentage of fees that will be paid as rewards uint16 public referralRewardRate; // stores if the referral system is turned on or off bool public referralsActivated; // stores individual referral rates mapping(address => uint16) public customReferralRewardRate; // stores uniswap forks status, index is the factory address mapping(address => bool) public forkActivated; // stores uniswap forks initCodes, index is the factory address mapping(address => bytes) public forkInitCode; /// @dev construct this contract /// @param _WETH address of WETH. /// @param _swapFee nominator for swapFee. Denominator = 10000 /// @param _referralRewardRate percentage of swapFee that are paid out as rewards /// @param _feeReceiver address that receives protocol fees /// @param _referralRegistry address of referral registry that stores referral anchors /// @param _zeroEx address of zeroX proxy contract to forward swaps constructor( address _WETH, uint16 _swapFee, uint16 _referralRewardRate, address payable _feeReceiver, IReferralRegistry _referralRegistry, address payable _zeroEx, address payable _oneInch ) public { WETH = _WETH; swapFee = _swapFee; referralRewardRate = _referralRewardRate; feeReceiver = _feeReceiver; referralRegistry = _referralRegistry; zeroEx = _zeroEx; oneInch = _oneInch; referralsActivated = true; } /// @dev execute swap directly on Uniswap/Pancake & simular forks /// @param swapData stores the swapData information /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactETHForTokens( SwapData calldata swapData, uint256 amountOutMin, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); amounts = _getAmountsOut(swapData.fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0])); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount of tokensIn /// @param amountOutMin minimum tokens to receive /// @param path Sell path. function swapExactTokensForETHSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amountIn); _swapSupportingFeeOnTransferTokens(swapData.fork, path, address(this)); uint256 amountOut = IERC20(WETH).balanceOf(address(this)); IWETH(WETH).withdraw(amountOut); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountOut, referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: LOW_SLIPPAGE"); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactTokensForTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountIn, referee, false ); amounts = _getAmountsOut(swapData.fork, swapAmount, path); require(amounts[amounts.length - 1] >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. /// @return amounts function swapExactTokensForETH( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); amounts = _getAmountsOut(swapData.fork, amountIn, path); (uint256 amountWithdraw, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[amounts.length - 1], referee, false ); require(amountWithdraw >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountWithdraw); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected amount of tokens out /// @param path Sell path. /// @return amounts function swapETHForExactTokens( SwapData calldata swapData, uint256 amountOut, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); amounts = _getAmountsIn(swapData.fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[0], referee, true ); require(amounts[0].add(feeAmount).add(referralReward) <= msg.value, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), amounts[0])); _swap(swapData.fork, amounts, path, msg.sender); // refund dust eth, if any if (msg.value > amounts[0].add(feeAmount).add(referralReward)) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0].add(feeAmount).add(referralReward)); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountIn amount if tokens In /// @param amountOutMin minimum tokens to receive /// @param path Sell path. function swapExactTokensForTokensSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountIn, referee, false ); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), swapAmount); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @return amounts function swapTokensForExactTokens( SwapData calldata swapData, uint256 amountOut, uint256 amountInMax, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { address referee = _getReferee(swapData.referee); amounts = _getAmountsIn(swapData.fork, amountOut, path); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amounts[0], referee, true ); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, msg.sender); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(path[0], path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOut expected tokens to receive /// @param amountInMax maximum tokens to send /// @param path Sell path. /// @return amounts function swapTokensForExactETH( SwapData calldata swapData, uint256 amountOut, uint256 amountInMax, address[] calldata path ) external whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, amountOut, referee, true ); amounts = _getAmountsIn(swapData.fork, amountOut.add(feeAmount).add(referralReward), path); require(amounts[0].add(feeAmount).add(referralReward) <= amountInMax, "FloozRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, _pairFor(swapData.fork, path[0], path[1]), amounts[0]); _swap(swapData.fork, amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(msg.sender, amountOut); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev execute swap directly on Uniswap/Pancake/... /// @param swapData stores the swapData information /// @param amountOutMin minimum expected tokens to receive /// @param path Sell path. function swapExactETHForTokensSupportingFeeOnTransferTokens( SwapData calldata swapData, uint256 amountOutMin, address[] calldata path ) external payable whenNotPaused isValidFork(swapData.fork) isValidReferee(swapData.referee) { require(path[0] == WETH, "FloozRouter: INVALID_PATH"); address referee = _getReferee(swapData.referee); (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); IWETH(WETH).deposit{value: swapAmount}(); assert(IWETH(WETH).transfer(_pairFor(swapData.fork, path[0], path[1]), swapAmount)); uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(msg.sender); _swapSupportingFeeOnTransferTokens(swapData.fork, path, msg.sender); require( IERC20(path[path.length - 1]).balanceOf(msg.sender).sub(balanceBefore) >= amountOutMin, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); if (feeAmount.add(referralReward) > 0) _withdrawFeesAndRewards(address(0), path[path.length - 1], referee, feeAmount, referralReward); } /// @dev returns the referee for a given address, if new, registers referee /// @param referee the address of the referee for msg.sender /// @return referee address from referral registry function _getReferee(address referee) internal returns (address) { address sender = msg.sender; if (!referralRegistry.hasUserReferee(sender) && referee != address(0)) { referralRegistry.createReferralAnchor(sender, referee); } return referralRegistry.getUserReferee(sender); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( address fork, uint256[] memory amounts, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; IPancakePair(_pairFor(fork, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens( address fork, address[] memory path, address _to ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(_pairFor(fork, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = _getAmountOut(amountInput, reserveInput, reserveOutput); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? _pairFor(fork, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } /// @dev Executes a swap on 1inch /// @param swapData encoded swap data function executeOneInchSwap(ExternalSwapData calldata swapData) external payable nonReentrant whenNotPaused isValidReferee(swapData.referee) { address referee = _getReferee(swapData.referee); uint256 balanceBefore; if (swapData.toToken == address(0)) { balanceBefore = msg.sender.balance; } else { balanceBefore = IERC20(swapData.toToken).balanceOf(msg.sender); } if (!swapData.fee) { // execute without fees if (swapData.fromToken != address(0)) { IERC20(swapData.fromToken).transferFrom(msg.sender, address(this), swapData.amountFrom); IERC20(swapData.fromToken).approve(oneInch, swapData.amountFrom); } // executes trade and sends toToken to defined recipient (bool success, ) = address(oneInch).call{value: msg.value}(swapData.data); require(success, "FloozRouter: REVERTED"); } else { // Swap from ETH if (msg.value > 0 && swapData.fromToken == address(0)) { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); (bool success, ) = address(oneInch).call{value: swapAmount}(swapData.data); require(success, "FloozRouter: REVERTED"); _withdrawFeesAndRewards(address(0), swapData.toToken, referee, feeAmount, referralReward); // Swap from token } else { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, swapData.amountFrom, referee, false ); IERC20(swapData.fromToken).transferFrom(msg.sender, address(this), swapAmount); IERC20(swapData.fromToken).approve(oneInch, swapAmount); (bool success, ) = address(oneInch).call(swapData.data); require(success, "FloozRouter: REVERTED"); _withdrawFeesAndRewards(swapData.fromToken, swapData.toToken, referee, feeAmount, referralReward); } uint256 balanceAfter; if (swapData.toToken == address(0)) { balanceAfter = msg.sender.balance; } else { balanceAfter = IERC20(swapData.toToken).balanceOf(msg.sender); } require(balanceAfter.sub(balanceBefore) >= swapData.minOut, "FloozRouter: INSUFFICIENT_OUTPUT"); } } /// @dev Executes a swap on 0x /// @param swapData encoded swap data function executeZeroExSwap(ExternalSwapData calldata swapData) external payable nonReentrant whenNotPaused isValidReferee(swapData.referee) { address referee = _getReferee(swapData.referee); uint256 balanceBefore; if (swapData.toToken == address(0)) { balanceBefore = msg.sender.balance; } else { balanceBefore = IERC20(swapData.toToken).balanceOf(msg.sender); } if (!swapData.fee) { if (msg.value > 0 && swapData.fromToken == address(0)) { (bool success, ) = zeroEx.call{value: msg.value}(swapData.data); require(success, "FloozRouter: REVERTED"); TransferHelper.safeTransfer( swapData.toToken, msg.sender, IERC20(swapData.toToken).balanceOf(address(this)) ); } else { IERC20(swapData.fromToken).transferFrom(msg.sender, address(this), swapData.amountFrom); IERC20(swapData.fromToken).approve(zeroEx, swapData.amountFrom); (bool success, ) = zeroEx.call(swapData.data); require(success, "FloozRouter: REVERTED"); if (swapData.toToken == address(0)) { TransferHelper.safeTransferETH(msg.sender, address(this).balance); } else { TransferHelper.safeTransfer( swapData.toToken, msg.sender, IERC20(swapData.toToken).balanceOf(address(this)) ); } } } else { // Swap from ETH if (msg.value > 0 && swapData.fromToken == address(0)) { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, msg.value, referee, false ); (bool success, ) = zeroEx.call{value: swapAmount}(swapData.data); require(success, "FloozRouter: REVERTED"); TransferHelper.safeTransfer( swapData.toToken, msg.sender, IERC20(swapData.toToken).balanceOf(address(this)) ); _withdrawFeesAndRewards(address(0), swapData.toToken, referee, feeAmount, referralReward); // Swap from Token } else { (uint256 swapAmount, uint256 feeAmount, uint256 referralReward) = _calculateFeesAndRewards( swapData.fee, swapData.amountFrom, referee, false ); IERC20(swapData.fromToken).transferFrom(msg.sender, address(this), swapAmount); IERC20(swapData.fromToken).approve(zeroEx, swapAmount); (bool success, ) = zeroEx.call(swapData.data); require(success, "FloozRouter: REVERTED"); if (swapData.toToken == address(0)) { TransferHelper.safeTransferETH(msg.sender, address(this).balance); } else { TransferHelper.safeTransfer( swapData.toToken, msg.sender, IERC20(swapData.toToken).balanceOf(address(this)) ); } _withdrawFeesAndRewards(swapData.fromToken, swapData.toToken, referee, feeAmount, referralReward); } } uint256 balanceAfter; if (swapData.toToken == address(0)) { balanceAfter = msg.sender.balance; } else { balanceAfter = IERC20(swapData.toToken).balanceOf(msg.sender); } require(balanceAfter.sub(balanceBefore) >= swapData.minOut, "FloozRouter: INSUFFICIENT_OUTPUT"); } /// @dev calculates swap, fee & reward amounts /// @param fee boolean if fee will be applied or not /// @param amount total amount of tokens /// @param referee the address of the referee for msg.sender function _calculateFeesAndRewards( bool fee, uint256 amount, address referee, bool additiveFee ) internal view returns ( uint256 swapAmount, uint256 feeAmount, uint256 referralReward ) { uint16 swapFee = swapFee; // no fees for users above threshold if (!fee) { swapAmount = amount; } else { if (additiveFee) { swapAmount = amount; feeAmount = swapAmount.mul(FEE_DENOMINATOR).div(FEE_DENOMINATOR.sub(swapFee)).sub(amount); } else { feeAmount = amount.mul(swapFee).div(FEE_DENOMINATOR); swapAmount = amount.sub(feeAmount); } // calculate referral rates, if referee is not 0x if (referee != address(0) && referralsActivated) { uint16 referralRate = customReferralRewardRate[referee] > 0 ? customReferralRewardRate[referee] : referralRewardRate; referralReward = feeAmount.mul(referralRate).div(FEE_DENOMINATOR); feeAmount = feeAmount.sub(referralReward); } else { referralReward = 0; } } } /// @dev lets the admin register an Uniswap style fork function registerFork(address _factory, bytes calldata _initCode) external onlyOwner { require(!forkActivated[_factory], "FloozRouter: ACTIVE_FORK"); forkActivated[_factory] = true; forkInitCode[_factory] = _initCode; emit ForkCreated(_factory); } /// @dev lets the admin update an Uniswap style fork function updateFork( address _factory, bytes calldata _initCode, bool _activated ) external onlyOwner { forkActivated[_factory] = _activated; forkInitCode[_factory] = _initCode; emit ForkUpdated(_factory); } /// @dev lets the admin update the swapFee nominator function updateSwapFee(uint16 newSwapFee) external onlyOwner { swapFee = newSwapFee; emit SwapFeeUpdated(newSwapFee); } /// @dev lets the admin update the referral reward rate function updateReferralRewardRate(uint16 newReferralRewardRate) external onlyOwner { require(newReferralRewardRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); referralRewardRate = newReferralRewardRate; emit ReferralRewardRateUpdated(newReferralRewardRate); } /// @dev lets the admin update which address receives the protocol fees function updateFeeReceiver(address payable newFeeReceiver) external onlyOwner { feeReceiver = newFeeReceiver; emit FeeReceiverUpdated(newFeeReceiver); } /// @dev lets the admin update the status of the referral system function updateReferralsActivated(bool newReferralsActivated) external onlyOwner { referralsActivated = newReferralsActivated; emit ReferralsActivatedUpdated(newReferralsActivated); } /// @dev lets the admin set a new referral registry function updateReferralRegistry(address newReferralRegistry) external onlyOwner { referralRegistry = IReferralRegistry(newReferralRegistry); emit ReferralRegistryUpdated(newReferralRegistry); } /// @dev lets the admin set a custom referral rate function updateCustomReferralRewardRate(address account, uint16 referralRate) external onlyOwner returns (uint256) { require(referralRate <= FEE_DENOMINATOR, "FloozRouter: INVALID_RATE"); customReferralRewardRate[account] = referralRate; emit CustomReferralRewardRateUpdated(account, referralRate); } /// @dev returns the referee for a given user - 0x address if none function getUserReferee(address user) external view returns (address) { return referralRegistry.getUserReferee(user); } /// @dev returns if the given user has been referred or not function hasUserReferee(address user) external view returns (bool) { return referralRegistry.hasUserReferee(user); } /// @dev lets the admin withdraw ETH from the contract. function withdrawETH(address payable to, uint256 amount) external onlyOwner { TransferHelper.safeTransferETH(to, amount); } /// @dev lets the admin withdraw ERC20s from the contract. function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { TransferHelper.safeTransfer(token, to, amount); } /// @dev distributes fees & referral rewards to users function _withdrawFeesAndRewards( address tokenReward, address tokenOut, address referee, uint256 feeAmount, uint256 referralReward ) internal { if (tokenReward == address(0)) { TransferHelper.safeTransferETH(feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferETH(referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } else { TransferHelper.safeTransferFrom(tokenReward, msg.sender, feeReceiver, feeAmount); if (referralReward > 0) { TransferHelper.safeTransferFrom(tokenReward, msg.sender, referee, referralReward); emit ReferralRewardPaid(msg.sender, referee, tokenOut, tokenReward, referralReward); } } } /// @dev given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul((9970)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } /// @dev given an output amount of an asset and pair reserves, returns a required input amount of the other asset function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "FloozRouter: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(10000); uint256 denominator = reserveOut.sub(amountOut).mul(9970); amountIn = (numerator / denominator).add(1); } /// @dev performs chained getAmountOut calculations on any number of pairs function _getAmountsOut( address fork, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(fork, path[i], path[i + 1]); amounts[i + 1] = _getAmountOut(amounts[i], reserveIn, reserveOut); } } /// @dev performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "FloozRouter: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = _getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } /// @dev fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = PancakeLibrary.sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPancakePair(_pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } /// @dev calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { (address token0, address token1) = PancakeLibrary.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), forkInitCode[factory] // init code hash ) ) ) ); } /// @dev lets the admin pause this contract function pause() external onlyOwner { _pause(); } /// @dev lets the admin unpause this contract function unpause() external onlyOwner { _unpause(); } /// @dev allows to receive ETH on the contract receive() external payable {} modifier isValidFork(address factory) { require(forkActivated[factory], "FloozRouter: INVALID_FACTORY"); _; } modifier isValidReferee(address referee) { require(msg.sender != referee, "FloozRouter: SELF_REFERRAL"); _; } } pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IWETH.sol"; contract FeeReceiverMultichain is Ownable { address public WETH; constructor(address _WETH) public { WETH = _WETH; } /// @dev converts WETH to ETH function unwrapWETH() public { uint256 balance = IWETH(WETH).balanceOf(address(this)); require(balance > 0, "FeeReceiver: Nothing to unwrap"); IWETH(WETH).withdraw(balance); } /// @dev lets the owner withdraw ETH from the contract function withdrawETH(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @dev lets the owner withdraw any ERC20 Token from the contract function withdrawERC20Token( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /// @dev allows to receive ETH on this contract receive() external payable {} } pragma solidity =0.6.6; import "@openzeppelin/contracts/access/Ownable.sol"; contract ReferralRegistry is Ownable { event ReferralAnchorCreated(address indexed user, address indexed referee); event ReferralAnchorUpdated(address indexed user, address indexed referee); event AnchorManagerUpdated(address account, bool isManager); // stores addresses which are allowed to create new anchors mapping(address => bool) public isAnchorManager; // stores the address that referred a given user mapping(address => address) public referralAnchor; /// @dev create a new referral anchor on the registry /// @param _user address of the user /// @param _referee address wich referred the user function createReferralAnchor(address _user, address _referee) external onlyAnchorManager { require(referralAnchor[_user] == address(0), "ReferralRegistry: ANCHOR_EXISTS"); referralAnchor[_user] = _referee; emit ReferralAnchorCreated(_user, _referee); } /// @dev allows admin to overwrite anchor /// @param _user address of the user /// @param _referee address wich referred the user function updateReferralAnchor(address _user, address _referee) external onlyOwner { referralAnchor[_user] = _referee; emit ReferralAnchorUpdated(_user, _referee); } /// @dev allows admin to grant/remove anchor priviliges /// @param _anchorManager address of the anchor manager /// @param _isManager add or remove privileges function updateAnchorManager(address _anchorManager, bool _isManager) external onlyOwner { isAnchorManager[_anchorManager] = _isManager; emit AnchorManagerUpdated(_anchorManager, _isManager); } function getUserReferee(address _user) external view returns (address) { return referralAnchor[_user]; } function hasUserReferee(address _user) external view returns (bool) { return referralAnchor[_user] != address(0); } modifier onlyAnchorManager() { require(isAnchorManager[msg.sender], "ReferralRegistry: FORBIDDEN"); _; } }
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function _getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "FloozRouter: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "FloozRouter: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul((9970)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; }
5,862,700
/** *Submitted for verification at Etherscan.io on 2021-05-07 */ // Sources flattened with hardhat v2.0.3 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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); } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File interfaces/defidollar/ICore.sol pragma solidity ^0.6.0; interface ICore { function mint( uint256 btc, address account, bytes32[] calldata merkleProof ) external returns (uint256); function redeem(uint256 btc, address account) external returns (uint256); function btcToBbtc(uint256 btc) external view returns (uint256, uint256); function bBtcToBtc(uint256 bBtc) external view returns (uint256 btc, uint256 fee); function pricePerShare() external view returns (uint256); function setGuestList(address guestlist) external; function collectFee() external; function owner() external view returns (address); } // File contracts/badger-core/Disperse.sol pragma solidity ^0.6.0; contract Disperse is Initializable { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event PayeeAdded(address account, uint256 shares); event PaymentReleased(address token, address to, uint256 amount); address public constant core = 0x2A8facc9D49fBc3ecFf569847833C380A13418a8; address public constant ibbtc = 0xc4E15973E6fF2A35cC804c2CF9D2a1b817a8b40F; uint256 private _totalShares; mapping(address => uint256) private _shares; address[] private _payees; mapping(address => bool) private _isPayee; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function initialize (address[] memory payees, uint256[] memory shares) public initializer { // solhint-disable-next-line max-line-length require(payees.length == shares.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares[i]); } } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } function payees() public view returns (address[] memory) { return _payees; } function isPayee(address account) public view returns (bool) { return _isPayee[account]; } /// @dev Disperse balance of a given token in contract among recipients function disperseToken(IERC20Upgradeable token) external { // If dispersing IBBTC, collect the fee first if (address(token) == ibbtc) { ICore(core).collectFee(); } require(_isPayee[msg.sender], "onlyPayees"); uint256 tokenBalance = token.balanceOf(address(this)); for (uint256 i = 0; i < _payees.length; i++) { address payee = _payees[i]; uint256 toPayee = tokenBalance.mul(_shares[payee]).div(_totalShares); token.safeTransfer(payee, toPayee); emit PaymentReleased(address(token), payee, toPayee); } } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _isPayee[account] = true; _shares[account] = shares_; _totalShares = _totalShares.add(shares_); emit PayeeAdded(account, shares_); } }
Disperse balance of a given token in contract among recipients If dispersing IBBTC, collect the fee first
function disperseToken(IERC20Upgradeable token) external { if (address(token) == ibbtc) { ICore(core).collectFee(); } require(_isPayee[msg.sender], "onlyPayees"); uint256 tokenBalance = token.balanceOf(address(this)); for (uint256 i = 0; i < _payees.length; i++) { address payee = _payees[i]; uint256 toPayee = tokenBalance.mul(_shares[payee]).div(_totalShares); token.safeTransfer(payee, toPayee); emit PaymentReleased(address(token), payee, toPayee); } }
15,405,212
pragma solidity ^0.4.18; import "../ownership/Ownable.sol"; contract DataStore is Ownable{ /**** Storage Types *******/ mapping(bytes32 => uint256) private mUIntStorage; mapping(bytes32 => string) private mStringStorage; mapping(bytes32 => address) private mAddressStorage; mapping(bytes32 => bytes) private mBytesStorage; mapping(bytes32 => bool) private mBooleanStorage; mapping(bytes32 => int256) private mIntStorage; modifier onlyLatest() { // The owner is only allowed to set the storage upon deployment to register the initial contracts, afterwards their direct access is disabled if (msg.sender == owner) { require(mBooleanStorage[keccak256("contract.storage.initialised")] == false); } else { // Make sure the access is permitted to only contracts in our Dapp require(mAddressStorage[keccak256("contract.address", msg.sender)] != 0x0); } _; } /**** Get Methods ***********/ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return mAddressStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return mUIntStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return mStringStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return mBytesStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return mBooleanStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return mIntStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyLatest external { mAddressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyLatest external { mUIntStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyLatest external { mStringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyLatest external { mBytesStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyLatest external { mBooleanStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyLatest external { mIntStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyLatest external { delete mAddressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyLatest external { delete mUIntStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyLatest external { delete mStringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyLatest external { delete mBytesStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyLatest external { delete mBooleanStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyLatest external { delete mIntStorage[_key]; } }
_key The key for the record
function deleteAddress(bytes32 _key) onlyLatest external { delete mAddressStorage[_key]; }
2,558,316
pragma solidity ^0.4.17; library SafeMathMod { // Partial SafeMath Library function mul(uint256 a, uint256 b) constant internal returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant internal returns(uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256 c) { require((c = a - b) < a); } function add(uint256 a, uint256 b) internal pure returns(uint256 c) { require((c = a + b) > a); } } contract Usdcoins { //is inherently ERC20 using SafeMathMod for uint256; /** * @constant name The name of the token * @constant symbol The symbol used to display the currency * @constant decimals The number of decimals used to dispay a balance * @constant totalSupply The total number of tokens times 10^ of the number of decimals * @constant MAX_UINT256 Magic number for unlimited allowance * @storage balanceOf Holds the balances of all token holders * @storage allowed Holds the allowable balance to be transferable by another address. */ address owner; string constant public name = "USDC"; string constant public symbol = "USDC"; uint256 constant public decimals = 18; uint256 constant public totalSupply = 100000000e18; uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event TransferFrom(address indexed _spender, address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function() payable { revert(); } function Usdcoins() public { balanceOf[msg.sender] = totalSupply; owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev function that sells available tokens */ function transfer(address _to, uint256 _value) public returns(bool success) { /* Ensures that tokens are not sent to address "0x0" */ require(_to != address(0)); /* Prevents sending tokens directly to contracts. */ /* SafeMathMOd.sub will throw if there is not enough balance and if the transfer value is 0. */ balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { /* Ensures that tokens are not sent to address "0x0" */ require(_to != address(0)); /* Ensures tokens are not sent to this contract */ uint256 allowance = allowed[_from][msg.sender]; /* Ensures sender has enough available allowance OR sender is balance holder allowing single transsaction send to contracts*/ require(_value <= allowance || _from == msg.sender); /* Use SafeMathMod to add and subtract from the _to and _from addresses respectively. Prevents under/overflow and 0 transfers */ balanceOf[_to] = balanceOf[_to].add(_value); balanceOf[_from] = balanceOf[_from].sub(_value); /* Only reduce allowance if not MAX_UINT256 in order to save gas on unlimited allowance */ /* Balance holder does not need allowance to send from self. */ if (allowed[_from][msg.sender] != MAX_UINT256 && _from != msg.sender) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); } Transfer(_from, _to, _value); return true; } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartyTransfer(address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiPartyTransferFrom(address _from, address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns(bool success) { /* Ensures address "0x0" is not assigned allowance. */ require(_spender != address(0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns(uint256 remaining) { remaining = allowed[_owner][_spender]; } function isNotContract(address _addr) private view returns(bool) { uint length; assembly { /* retrieve the size of the code on target address, this needs assembly */ length: = extcodesize(_addr) } return (length == 0); } }
_owner The address of the account owning tokens _spender The address of the account able to transfer the tokens return Amount of remaining tokens allowed to spent/
function allowance(address _owner, address _spender) public view returns(uint256 remaining) { remaining = allowed[_owner][_spender]; } }
632,361
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/Swap/BaseV1-periphery.sol
create the pair if it doesn"t exist yet
function _addLiquidity( address tokenA, address tokenB, bool stable, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal returns (uint amountA, uint amountB) { require(amountADesired >= amountAMin); require(amountBDesired >= amountBMin); address _pair = IBaseV1Factory(factory).getPair(tokenA, tokenB, stable); if (_pair == address(0)) { _pair = IBaseV1Factory(factory).createPair(tokenA, tokenB, stable); } (uint reserveA, uint reserveB) = getReserves(tokenA, tokenB, stable); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = quoteLiquidity(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, "BaseV1Router: INSUFFICIENT_B_AMOUNT"); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = quoteLiquidity(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, "BaseV1Router: INSUFFICIENT_A_AMOUNT"); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
2,595,464
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributorV3.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update * @param _isBorrow whether to update the borrow state */ function _updateRewards( address[] memory _holders, address[] memory _iTokens, bool _isBorrow ) internal { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, _isBorrow); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], _isBorrow); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _suppliediTokens The _suppliediTokens to claim from * @param _borrowediTokens The _borrowediTokens to claim from */ function claimRewards( address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens ) external override { _updateRewards(_holders, _suppliediTokens, false); _updateRewards(_holders, _borrowediTokens, true); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IInterestRateModelInterface.sol"; import "./IControllerInterface.sol"; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function mintAndEnterMarket(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IiToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } function rpow( uint256 x, uint256 n, uint256 base ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IControllerInterface.sol"; import "./interface/IPriceOracle.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Only expect to be called by iToken contract. * @dev Add the market to the account's markets list for liquidity calculations * @param _account The address of the account to modify */ function enterMarketFromiToken(address _account) external override { require( _enterMarket(msg.sender, _account), "enterMarketFromiToken: Only can be called by a supported iToken!" ); } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev Calculates the current borrow interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev Calculates the current supply interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); }
Hook function before iToken `seize()` Checks if the liquidator should be allowed to seize the collateral iToken Will `revert()` if any check fails _iTokenCollateral The collateral iToken to be seize _iTokenBorrowed The iToken was borrowed _liquidator The account which has repaid the borrowed iToken _borrower The account which has borrowed _seizeAmount The amount of collateral iToken to seize/ Markets must have been listed Sanity Check the controllers Update the Reward Distribution Supply state on collateral Update reward of liquidator and borrower on collateral
function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; }
1,318,117
./partial_match/4/0x32b3BA3B0F8be8eD95118604a8c7178BFD9F5905/sources/UniswapOrbit.sol
https:docs.synthetix.io/contracts/source/interfaces/istakingrewards Views Mutative
interface IStakingRewards { function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } }
8,708,078
./full_match/1/0x9a8A1D7Eac06871f60158f127704F3910613E3c3/sources/contracts/adapters/SanTokenERC4626Adapter.sol
Converts an amount of `shares` to an assets amount with potential exit slippage taken into account
function _convertToAssetsWithSlippage(uint256 shares) internal view returns (uint256 assets) { (uint256 sanRate, uint256 slippage) = _estimateSanRate(); assets = shares.mulDiv((_BASE_9 - slippage) * sanRate, _BASE_27, MathUpgradeable.Rounding.Down); }
3,219,229
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./WonkaLibrary.sol"; import "./WonkaEngineMetadata.sol"; /// @title An Ethereum contract that contains the functionality for a rules engine /// @author Aaron Kendall /// @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs /// @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library contract WonkaEngineRuleSets { using WonkaLibrary for *; // An enum for the type of rules currently supported enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, Populated, InDomain, Assign, OpAdd, OpSub, OpMult, OpDiv, CustomOp, MAX_TYPE } RuleTypes constant defaultType = RuleTypes.IsEqual; string constant blankValue = ""; uint constant CONST_CUSTOM_OP_ARGS = 4; address public rulesMaster; uint public ruleCounter; uint public lastRuleId; bool orchestrationMode; bytes32 defaultTargetSource; WonkaEngineMetadata metadata; // The cache map for rulesets mapping(address => mapping(bytes32 => WonkaLibrary.WonkaRuleSet)) private ruleTreesMap; // The cache list for rulesets mapping(address => bytes32[]) private ruleTreesList; // The cache of records that are owned by "rulers" and that are validated when invoking a rule tree mapping(address => mapping(bytes32 => string)) currentRecords; // The cache of available sources for retrieving and setting attribute values found on other contracts mapping(bytes32 => WonkaLibrary.WonkaSource) sourceMap; // The cache of available sources for calling 'op' methods (i.e., that contain special logic to implement a custom operator) mapping(bytes32 => WonkaLibrary.WonkaSource) opMap; // For the function splitStr(...) // Currently unsure how the function will perform in a multithreaded scenario bytes splitTempStr; // temporarily holds the string part until a space is received /// @dev Constructor for the rules engine /// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later constructor(address _metadataAddr) { orchestrationMode = false; rulesMaster = msg.sender; ruleCounter = lastRuleId = 1; metadata = WonkaEngineMetadata(_metadataAddr); } modifier onlyEngineOwner() { // NOTE: Should be altered later // require(msg.sender == rulesMaster, "No exec perm"); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } modifier onlyEngineOwnerOrTreeOwner(address _RTOwner) { // NOTE: To be addressed later // require((msg.sender == rulesMaster) || (msg.sender == _RTOwner), "No exec perm"); // NOTE: To be addressed later // require(ruletrees[_RTOwner].isValue == true, "No RT"); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } /// @dev This method will add a new custom operator to the cache. /// @notice function addCustomOp(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName) public onlyEngineOwner { opMap[srcName] = WonkaLibrary.WonkaSource({ sourceName: srcName, status: sts, contractAddress: cntrtAddr, methodName: methName, setMethodName: "", isValue: true }); } /// @dev This method will add a new RuleSet to the cache and to the indicated RuleTree. Using flagFailImmediately is not recommended and will likely be deprecated in the near future. /// @notice Currently, a RuleSet can only belong to one RuleTree and be a child of one parent RuleSet, though there are plans to have a RuleSet capable of being shared among parents function addRuleSet(address ruler, bytes32 ruleSetName, string memory desc, bytes32 parentRSName, bool severeFailureFlag, bool useAndOperator, bool flagFailImmediately) public onlyEngineOwnerOrTreeOwner(ruler) { if (parentRSName != "") { require(ruleTreesMap[ruler][parentRSName].isValue == true, "No parent RS"); } require(ruleTreesMap[ruler][ruleSetName].isValue == false, "The specified RuleSet with the provided ID already exists."); ruleTreesList[ruler].push(ruleSetName); WonkaLibrary.WonkaRuleSet storage NewRuleSet = ruleTreesMap[ruler][ruleSetName]; NewRuleSet.ruleSetId = ruleSetName; NewRuleSet.description = desc; NewRuleSet.parentRuleSetId = parentRSName; NewRuleSet.severeFailure = severeFailureFlag; NewRuleSet.andOp = useAndOperator; NewRuleSet.failImmediately = flagFailImmediately; NewRuleSet.evalRuleList = new uint[](0); NewRuleSet.assertiveRuleList = new uint[](0); NewRuleSet.childRuleSetList = new bytes32[](0); NewRuleSet.isLeaf = true; NewRuleSet.isValue = true; if (parentRSName != "") { ruleTreesMap[ruler][parentRSName].childRuleSetList.push(ruleSetName); ruleTreesMap[ruler][parentRSName].isLeaf = false; } } /// @dev This method will add a new Rule to the indicated RuleSet /// @notice Currently, a Rule can only belong to one RuleSet function addRule(address ruler, bytes32 ruleSetId, bytes32 ruleName, bytes32 attrName, uint rType, string memory rVal, bool notFlag, bool passiveFlag) public onlyEngineOwnerOrTreeOwner(ruler) { require(ruleTreesMap[ruler][ruleSetId].isValue == true, "No RS"); require(metadata.getAttribute(attrName).isValue, "No Attr (A)"); require(rType < uint(RuleTypes.MAX_TYPE), "No RuleType"); uint currRuleId = lastRuleId = ruleCounter; ruleCounter = ruleCounter + 1; if (passiveFlag) { ruleTreesMap[ruler][ruleSetId].evalRuleList.push(currRuleId); ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].ruleId = currRuleId; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].name = ruleName; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].ruleType = rType; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].targetAttrName = attrName; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].ruleValue = rVal; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].ruleDomainKeys = new string[](0); ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].customOpArgs = new bytes32[](CONST_CUSTOM_OP_ARGS); ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].parentRuleSetId = ruleSetId; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].notOpFlag = notFlag; ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId].isPassiveFlag = passiveFlag; bool isOpRule = ((uint(RuleTypes.OpAdd) == rType) || (uint(RuleTypes.OpSub) == rType) || (uint(RuleTypes.OpMult) == rType) || (uint(RuleTypes.OpDiv) == rType) || (uint(RuleTypes.CustomOp) == rType)); if ( (uint(RuleTypes.InDomain) == rType) || isOpRule) { splitStrIntoMap(rVal, ",", ruleTreesMap[ruler][ruleSetId].evaluativeRules[currRuleId], isOpRule); } } else { ruleTreesMap[ruler][ruleSetId].assertiveRuleList.push(currRuleId); WonkaLibrary.WonkaRule storage NewRule = ruleTreesMap[ruler][ruleSetId].assertiveRules[currRuleId]; NewRule.ruleId = currRuleId; NewRule.name = ruleName; NewRule.ruleType = rType; NewRule.targetAttrName = attrName; NewRule.ruleValue = rVal; NewRule.ruleDomainKeys = new string[](0); NewRule.customOpArgs = new bytes32[](CONST_CUSTOM_OP_ARGS); NewRule.parentRuleSetId = ruleSetId; NewRule.notOpFlag = notFlag; NewRule.isPassiveFlag = passiveFlag; } } /// @dev This method will supply the args to the last rule added (of type Custom Operator) /// @notice Currently, a Rule can only belong to one RuleSet function addRuleCustomOpArgs(address ruler, bytes32 ruleSetId, bytes32 arg1, bytes32 arg2, bytes32 arg3, bytes32 arg4) public onlyEngineOwnerOrTreeOwner(ruler) { require(ruleTreesMap[ruler][ruleSetId].isValue == true, "No RS"); require(ruleTreesMap[ruler][ruleSetId].evaluativeRules[lastRuleId].ruleType == uint(RuleTypes.CustomOp), "LR not CO"); ruleTreesMap[ruler][ruleSetId].evaluativeRules[lastRuleId].customOpArgs[0] = arg1; ruleTreesMap[ruler][ruleSetId].evaluativeRules[lastRuleId].customOpArgs[1] = arg2; ruleTreesMap[ruler][ruleSetId].evaluativeRules[lastRuleId].customOpArgs[2] = arg3; ruleTreesMap[ruler][ruleSetId].evaluativeRules[lastRuleId].customOpArgs[3] = arg4; } /// @dev This method will add a new source to the mapping cache. /// @notice function addSource(bytes32 srcName, bytes32 sts, address cntrtAddr, bytes32 methName, bytes32 setMethName) public onlyEngineOwner { sourceMap[srcName] = WonkaLibrary.WonkaSource({ sourceName: srcName, status: sts, contractAddress: cntrtAddr, methodName: methName, setMethodName: setMethName, isValue: true }); } /// @dev This method will invoke one RuleSet within a RuleTree when validating a stored record /// @notice This method will return a boolean that assists with traversing the RuleTree function executeWithReport(address ruler, bytes32 rsId, WonkaLibrary.WonkaRuleReport memory ruleReport) public returns (bool executeSuccess) { return executeWithReport(ruler, ruleTreesMap[ruler][rsId], ruleReport); } /// @dev This method will invoke one RuleSet within a RuleTree when validating a stored record /// @notice This method will return a boolean that assists with traversing the RuleTree function executeWithReport(address ruler, WonkaLibrary.WonkaRuleSet storage targetRuleSet, WonkaLibrary.WonkaRuleReport memory ruleReport) private returns (bool executeSuccess) { executeSuccess = true; emit WonkaLibrary.CallRuleSet(ruler, targetRuleSet.ruleSetId); /* * NOTE: Should be supported? if (transStateInd[ruletrees[ruler].ruleTreeId]) { require(transStateMap[ruletrees[ruler].ruleTreeId].isTransactionConfirmed(), "No conf trx"); require(transStateMap[ruletrees[ruler].ruleTreeId].isExecutor(ruler), "No exec perm"); } */ bool tempResult = false; bool tempSetResult = true; bool useAndOp = targetRuleSet.andOp; bool failImmediately = targetRuleSet.failImmediately; bool severeFailure = targetRuleSet.severeFailure; // Now invoke the rules for (uint idx = 0; idx < targetRuleSet.evalRuleList.length; idx++) { WonkaLibrary.WonkaRule storage tempRule = targetRuleSet.evaluativeRules[targetRuleSet.evalRuleList[idx]]; tempResult = executeWithReport(ruler, tempRule, ruleReport); if (failImmediately) require(tempResult); if (idx == 0) { tempSetResult = tempResult; } else { if (useAndOp) tempSetResult = (tempSetResult && tempResult); else tempSetResult = (tempSetResult || tempResult); } } executeSuccess = tempSetResult; if (!executeSuccess) { emit WonkaLibrary.RuleSetError(ruler, targetRuleSet.ruleSetId, severeFailure); } if (targetRuleSet.isLeaf && severeFailure) return executeSuccess; if (executeSuccess && (targetRuleSet.childRuleSetList.length > 0)) { // Now invoke the rulesets for (uint rsIdx = 0; rsIdx < targetRuleSet.childRuleSetList.length; rsIdx++) { tempResult = executeWithReport(ruler, ruleTreesMap[ruler][targetRuleSet.childRuleSetList[rsIdx]], ruleReport); executeSuccess = (executeSuccess && tempResult); } } else executeSuccess = true; // NOTE: Should the transaction state be reset automatically upon the completion of the transaction? //if (transStateInd[ruletrees[ruler].ruleTreeId]) { // transStateMap[ruletrees[ruler].ruleTreeId].revokeAllConfirmations(); //} } /// @dev This method will invoke one Rule within a RuleSet when validating a stored record /// @notice This method will return a boolean that assists with traversing the RuleTree function executeWithReport(address ruler, WonkaLibrary.WonkaRule storage targetRule, WonkaLibrary.WonkaRuleReport memory ruleReport) private returns (bool ruleResult) { ruleResult = true; uint testNumValue = 0; uint ruleNumValue = 0; string memory tempValue = getValueOnRecord(ruler, targetRule.targetAttrName); bool almostOpInd = false; emit WonkaLibrary.CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType); if (metadata.getAttribute(targetRule.targetAttrName).isNumeric) { testNumValue = tempValue.parseInt(0); ruleNumValue = targetRule.ruleValue.parseInt(0); // NOTE: Too expensive to deploy? // if (keccak256(abi.encodePacked(targetRule.ruleValue)) != keccak256(abi.encodePacked("NOW"))) { // This indicates that we are doing a timestamp comparison with the value for NOW (and maybe looking for a window of one day ahead) if (metadata.getAttribute(targetRule.targetAttrName).isString && metadata.getAttribute(targetRule.targetAttrName).isNumeric && (ruleNumValue <= 1)) { if (ruleNumValue == 1) { almostOpInd = true; } ruleNumValue = block.timestamp + (ruleNumValue * 1 days); } // This indicates that we are doing a block number comparison (i.e., the hex number is the keccak256() result for the string "BLOCKNUMOP") else if (keccak256(abi.encodePacked(targetRule.ruleValue)) == keccak256(abi.encodePacked("00000"))) { ruleNumValue = block.number; } } if (almostOpInd) { ruleResult = ((testNumValue > block.timestamp) && (testNumValue < ruleNumValue)); } else if (uint(RuleTypes.IsEqual) == targetRule.ruleType) { if (metadata.getAttribute(targetRule.targetAttrName).isNumeric) { ruleResult = (testNumValue == ruleNumValue); } else { ruleResult = (keccak256(abi.encodePacked(tempValue)) == keccak256(abi.encodePacked(targetRule.ruleValue))); } } else if (uint(RuleTypes.IsLessThan) == targetRule.ruleType) { if (metadata.getAttribute(targetRule.targetAttrName).isNumeric) ruleResult = (testNumValue < ruleNumValue); } else if (uint(RuleTypes.IsGreaterThan) == targetRule.ruleType) { if (metadata.getAttribute(targetRule.targetAttrName).isNumeric) ruleResult = (testNumValue > ruleNumValue); } else if (uint(RuleTypes.Populated) == targetRule.ruleType) { ruleResult = (keccak256(abi.encodePacked(tempValue)) != keccak256(abi.encodePacked(""))); } else if (uint(RuleTypes.InDomain) == targetRule.ruleType) { ruleResult = (keccak256(abi.encodePacked(targetRule.ruleValueDomain[tempValue])) == keccak256(abi.encodePacked("Y"))); } else if (uint(RuleTypes.Assign) == targetRule.ruleType) { setValueOnRecord(ruler, metadata.getAttribute(targetRule.targetAttrName).attrName, targetRule.ruleValue); } else if ( (uint(RuleTypes.OpAdd) == targetRule.ruleType) || (uint(RuleTypes.OpSub) == targetRule.ruleType) || (uint(RuleTypes.OpMult) == targetRule.ruleType) || (uint(RuleTypes.OpDiv) == targetRule.ruleType) ) { uint calculatedValue = calculateValue(ruler, targetRule); string memory convertedValue = calculatedValue.uintToBytes().bytes32ToString(); setValueOnRecord(ruler, metadata.getAttribute(targetRule.targetAttrName).attrName, convertedValue); } else if (uint(RuleTypes.CustomOp) == targetRule.ruleType) { bytes32 customOpName = ""; if (targetRule.ruleDomainKeys.length > 0) customOpName = targetRule.ruleDomainKeys[0].stringToBytes32(); bytes32[] memory argsDomain = new bytes32[](CONST_CUSTOM_OP_ARGS); for (uint idx = 0; idx < CONST_CUSTOM_OP_ARGS; ++idx) { if (idx < targetRule.customOpArgs.length) argsDomain[idx] = determineDomainValue(ruler, idx, targetRule).stringToBytes32(); else argsDomain[idx] = ""; } string memory customOpResult = opMap[customOpName].contractAddress.invokeCustomOperator(ruler, opMap[customOpName].methodName, argsDomain[0], argsDomain[1], argsDomain[2], argsDomain[3]); setValueOnRecord(ruler, metadata.getAttribute(targetRule.targetAttrName).attrName, customOpResult); } if (!ruleResult && ruleTreesMap[ruler][targetRule.parentRuleSetId].isLeaf) { emit WonkaLibrary.CallRule(ruler, targetRule.parentRuleSetId, targetRule.name, targetRule.ruleType); ruleReport.ruleSetIds[ruleReport.ruleFailCount] = targetRule.parentRuleSetId; ruleReport.ruleIds[ruleReport.ruleFailCount] = targetRule.name; ruleReport.ruleFailCount += 1; } } /// @dev This method will return the default source function getDefaultSource() public view returns (bytes32) { return defaultTargetSource; } /// @dev This method will return the data that composes a particular Rule function getRuleProps(address ruler, bytes32 rsId, bool evalRuleFlag, uint ruleIdx) public view returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory) { WonkaLibrary.WonkaRule storage targetRule = (evalRuleFlag) ? ruleTreesMap[ruler][rsId].evaluativeRules[ruleTreesMap[ruler][rsId].evalRuleList[ruleIdx]] : ruleTreesMap[ruler][rsId].assertiveRules[ruleTreesMap[ruler][rsId].assertiveRuleList[ruleIdx]]; return (targetRule.name, targetRule.ruleType, metadata.getAttribute(targetRule.targetAttrName).attrName, targetRule.ruleValue, targetRule.notOpFlag, targetRule.customOpArgs); } /// @dev This method will return the ID of a RuleSet that is the child of a parent RuleSet function getRuleSetChildId(address ruler, bytes32 rsId, uint rsChildIdx) public view returns (bytes32) { return ruleTreesMap[ruler][rsId].childRuleSetList[rsChildIdx]; } /// @dev This method will return the data that composes a particular RuleSet function getRuleSetProps(address ruler, bytes32 rsId) public view returns (string memory, bool, bool, uint, uint, uint) { return (ruleTreesMap[ruler][rsId].description, ruleTreesMap[ruler][rsId].severeFailure, ruleTreesMap[ruler][rsId].andOp, ruleTreesMap[ruler][rsId].evalRuleList.length, ruleTreesMap[ruler][rsId].assertiveRuleList.length, ruleTreesMap[ruler][rsId].childRuleSetList.length); } /// @dev This method will return the value for an Attribute that is currently stored within the ruler's record /// @notice This method should only be used for debugging purposes. function getValueOnRecord(address ruler, bytes32 key) public returns(string memory) { // NOTE: Likely to retire this check // require(ruletrees[ruler].isValue, "The provided user does not own anything on this instance of the contract."); require(metadata.getAttribute(key).isValue, "No Attr (G)"); if (!orchestrationMode) { return (currentRecords[ruler])[key]; } else { if (sourceMap[key].isValue){ return sourceMap[key].contractAddress.invokeValueRetrieval(ruler, sourceMap[key].methodName, key); } else if (sourceMap[defaultTargetSource].isValue){ return sourceMap[defaultTargetSource].contractAddress.invokeValueRetrieval(ruler, sourceMap[defaultTargetSource].methodName, key); } else { return blankValue; } } } /// @dev This method will indicate whether or not a particular source exists /// @notice This method should only be used for debugging purposes. function getIsSourceMapped(bytes32 key) public view returns(bool) { return sourceMap[key].isValue; } /// @dev This method will indicate whether or not the Orchestration mode has been enabled /// @notice This method should only be used for debugging purposes. function getOrchestrationMode() public view returns(bool) { return orchestrationMode; } /// @dev This method will set the flag as to whether or not the engine should run in Orchestration mode (i.e., use the sourceMap) function setOrchestrationMode(bool orchMode, bytes32 defSource) public onlyEngineOwner { orchestrationMode = orchMode; defaultTargetSource = defSource; } /// @dev This method will set an Attribute value on the record associated with the provided address/account /// @notice We do not currently check here to see if the value qualifies according to the Attribute's definition function setValueOnRecord(address ruler, bytes32 key, string memory value) public returns(string memory) { // NOTE: Likely to retire this check // require(ruletrees[ruler].isValue, "The provided user does not own anything on this instance of the contract."); require(metadata.getAttribute(key).isValue, "No Attr (S)"); if (!orchestrationMode) { (currentRecords[ruler])[key] = value; return (currentRecords[ruler])[key]; } else { bytes32 bytes32Value = value.stringToBytes32(); if (sourceMap[key].isValue && (keccak256(abi.encodePacked(sourceMap[key].setMethodName)) != keccak256(abi.encodePacked("")))) { return sourceMap[key].contractAddress.invokeValueSetter(ruler, sourceMap[key].setMethodName, key, bytes32Value); } else if (sourceMap[defaultTargetSource].isValue && (keccak256(abi.encodePacked(sourceMap[defaultTargetSource].setMethodName)) != keccak256(abi.encodePacked("")))){ return sourceMap[defaultTargetSource].contractAddress.invokeValueSetter(ruler, sourceMap[defaultTargetSource].setMethodName, key, bytes32Value); } else { return ""; } } } /*********************** * SUPPORT METHODS * ***********************/ /// @dev This method will calculate the value for a Rule according to its type (Add, Subtract, etc.) and its domain values /// @notice function calculateValue(address ruler, WonkaLibrary.WonkaRule storage targetRule) private returns (uint calcValue){ uint tmpValue = 0; uint finalValue = 0; for (uint i = 0; i < targetRule.ruleDomainKeys.length; i++) { bytes32 keyName = targetRule.ruleDomainKeys[i].stringToBytes32(); if (metadata.getAttribute(keyName).isValue) tmpValue = getValueOnRecord(ruler, keyName).parseInt(0); else tmpValue = targetRule.ruleDomainKeys[i].parseInt(0); if (i == 0) finalValue = tmpValue; else { if ( uint(RuleTypes.OpAdd) == targetRule.ruleType ) finalValue += tmpValue; else if ( uint(RuleTypes.OpSub) == targetRule.ruleType ) finalValue -= tmpValue; else if ( uint(RuleTypes.OpMult) == targetRule.ruleType ) finalValue *= tmpValue; else if ( uint(RuleTypes.OpDiv) == targetRule.ruleType ) finalValue /= tmpValue; } } calcValue = finalValue; } /// @dev This method will assist by returning the correct value, either a literal static value or one obtained through retrieval function determineDomainValue(address ruler, uint domainIdx, WonkaLibrary.WonkaRule storage targetRule) private returns (string memory retValue) { retValue = ""; bytes32 keyName = targetRule.customOpArgs[domainIdx]; if (metadata.getAttribute(keyName).isValue) retValue = getValueOnRecord(ruler, keyName); else retValue = keyName.bytes32ToString(); } /// @dev This method will parse a delimited string and insert them into the Domain map of a Rule /// @notice function splitStrIntoMap(string memory str, string memory delimiter, WonkaLibrary.WonkaRule storage targetRule, bool isOpRule) private { bytes memory b = bytes(str); //cast the string to bytes to iterate bytes memory delm = bytes(delimiter); splitTempStr = ""; for(uint i; i<b.length ; i++){ if(b[i] != delm[0]) { //check if a not space splitTempStr.push(b[i]); } else { string memory sTempVal = string(splitTempStr); targetRule.ruleValueDomain[sTempVal] = "Y"; if (isOpRule) targetRule.ruleDomainKeys.push(sTempVal); splitTempStr = ""; } } if(b[b.length-1] != delm[0]) { string memory sTempValLast = string(splitTempStr); targetRule.ruleValueDomain[sTempValLast] = "Y"; if (isOpRule) targetRule.ruleDomainKeys.push(sTempValLast); } } }
This method will indicate whether or not the Orchestration mode has been enabled This method should only be used for debugging purposes.
function getOrchestrationMode() public view returns(bool) { return orchestrationMode; }
5,547,195
./partial_match/1/0xDaf89c25009665f0C82363830FAdda1a89331686/sources/GemPepe.sol
Dividend-Paying Token Optional Interface Roger Wu (https://github.com/roger-wu) OPTIONAL functions for a dividend-paying token contract.
interface GemIDividend { function withdrawnDividendOf(address _owner) external view returns (uint256); function withdrawableDividendOf(address _owner) external view returns (uint256); function accumulativeDividendOf(address _owner, address _token) external returns (uint256); }
4,437,372
./full_match/42/0x735620c8876c4E65a4019F79b32d33500B17c1b5/sources/contracts/LightGeneralizedTCR.sol
Submit a reference to evidence. EVENT. _itemID The ID of the item which the evidence is related to. _evidence A link to an evidence using its URI./
function submitEvidence(bytes32 _itemID, string calldata _evidence) external { Item storage item = items[_itemID]; Request storage request = item.requests[item.requests.length - 1]; require(!request.resolved, "The dispute must not already be resolved."); uint256 evidenceGroupID = uint256( keccak256(abi.encodePacked(_itemID, item.requests.length - 1)) ); emit Evidence( request.arbitrator, evidenceGroupID, msg.sender, _evidence ); }
16,245,617
./full_match/80001/0x684da7e5DB428400D5D8b244511aDbc8eAFC87f2/sources/contracts/Vendor1.sol
Require para verificar se foi mandado MATICAtualiza ordem de compra: EMIT the event
function buyTokensMatic() public payable nonReentrant returns (uint256 tokenAmount) { require(isOpen,"is not allow this function yet"); require(msg.value > 0, "Send ETH to buy some tokens"); uint _amountToBuy = msg.value * SafeCast.toUint256(tokensPerMatic()); uint amountToBuy = _amountToBuy/(10*10**14); OrderBuy(amountToBuy,MATIC,msg.sender); emit BuyTokens(msg.sender, msg.value, amountToBuy); return amountToBuy; }
9,501,688
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol"; import "../IDerivativePriceFeed.sol"; /// @title ConvexCurveLpStakingWrapperPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for wrapped Convex-staked Curve LP tokens contract ConvexCurveLpStakingWrapperPriceFeed is IDerivativePriceFeed { ConvexCurveLpStakingWrapperFactory private immutable WRAPPER_FACTORY; constructor(address _wrapperFactory) public { WRAPPER_FACTORY = ConvexCurveLpStakingWrapperFactory(_wrapperFactory); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = WRAPPER_FACTORY.getCurveLpTokenForWrapper(_derivative); underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return WRAPPER_FACTORY.getCurveLpTokenForWrapper(_asset) != address(0); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IStakingWrapper interface /// @author Enzyme Council <[email protected]> interface IStakingWrapper { struct TotalHarvestData { uint128 integral; uint128 lastCheckpointBalance; } struct UserHarvestData { uint128 integral; uint128 claimableReward; } function claimRewardsFor(address _for) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function deposit(uint256 _amount) external; function depositTo(address _to, uint256 _amount) external; function withdraw(uint256 _amount, bool _claimRewards) external returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_); function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external; function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external; // STATE GETTERS function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_); function getRewardTokenCount() external view returns (uint256 count_); function getRewardTokens() external view returns (address[] memory rewardTokens_); function getTotalHarvestDataForRewardToken(address _rewardToken) external view returns (TotalHarvestData memory totalHarvestData_); function getUserHarvestDataForRewardToken(address _user, address _rewardToken) external view returns (UserHarvestData memory userHarvestData_); function isPaused() external view returns (bool isPaused_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../utils/AddressArrayLib.sol"; import "./IStakingWrapper.sol"; /// @title StakingWrapperBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for staking wrappers /// @dev Can be used as a base for both standard deployments and proxy targets. /// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol), /// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers) abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard { using AddressArrayLib for address[]; using SafeERC20 for ERC20; using SafeMath for uint256; event Deposited(address indexed from, address indexed to, uint256 amount); event PauseToggled(bool isPaused); event RewardsClaimed( address caller, address indexed user, address[] rewardTokens, uint256[] claimedAmounts ); event RewardTokenAdded(address token); event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral); event TotalHarvestLastCheckpointBalanceUpdated( address indexed rewardToken, uint256 lastCheckpointBalance ); event UserHarvestUpdated( address indexed user, address indexed rewardToken, uint256 integral, uint256 claimableReward ); event Withdrawn( address indexed caller, address indexed from, address indexed to, uint256 amount ); uint8 private constant DEFAULT_DECIMALS = 18; uint256 private constant INTEGRAL_PRECISION = 1e18; address internal immutable OWNER; // Paused stops new deposits and checkpoints bool private paused; address[] private rewardTokens; mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData; mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData; modifier onlyOwner() { require(msg.sender == OWNER, "Only owner callable"); _; } constructor( address _owner, string memory _tokenName, string memory _tokenSymbol ) public ERC20(_tokenName, _tokenSymbol) { OWNER = _owner; } /// @notice Toggles pause for deposit and harvesting new rewards /// @param _isPaused True if next state is paused, false if unpaused function togglePause(bool _isPaused) external onlyOwner { paused = _isPaused; emit PauseToggled(_isPaused); } //////////////////////////// // DEPOSITOR INTERACTIONS // //////////////////////////// // CLAIM REWARDS /// @notice Claims all rewards for a given account /// @param _for The account for which to claim rewards /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user function claimRewardsFor(address _for) external override nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __checkpointAndClaim(_for); } // DEPOSIT /// @notice Deposits tokens to be staked, minting staking token to sender /// @param _amount The amount of tokens to deposit function deposit(uint256 _amount) external override { __deposit(msg.sender, msg.sender, _amount); } /// @notice Deposits tokens to be staked, minting staking token to a specified account /// @param _to The account to receive staking tokens /// @param _amount The amount of tokens to deposit function depositTo(address _to, uint256 _amount) external override { __deposit(msg.sender, _to, _amount); } /// @dev Helper to deposit tokens to be staked function __deposit( address _from, address _to, uint256 _amount ) private nonReentrant { require(!isPaused(), "__deposit: Paused"); // Checkpoint before minting __checkpoint([_to, address(0)]); _mint(_to, _amount); __depositLogic(_from, _amount); emit Deposited(_from, _to, _amount); } // WITHDRAWAL /// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards /// @param _amount The amount of tokens to withdraw /// @param _claimRewards True if accrued rewards should be claimed /// @return rewardTokens_ The reward tokens /// @return claimedAmounts_ The reward token amounts claimed /// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim function withdraw(uint256 _amount, bool _claimRewards) external override returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { return __withdraw(msg.sender, msg.sender, _amount, _claimRewards); } /// @notice Withdraws staked tokens, returning tokens to a specified account, /// and optionally claims rewards to the staked token holder /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw function withdrawTo( address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { __withdraw(msg.sender, _to, _amount, _claimRewardsToHolder); } /// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB, /// and optionally claims rewards to the staked token holder /// @param _onBehalf The account on behalf to withdraw /// @param _to The account to receive tokens /// @param _amount The amount of tokens to withdraw /// @dev The caller must have an adequate ERC20.allowance() for _onBehalf function withdrawToOnBehalf( address _onBehalf, address _to, uint256 _amount, bool _claimRewardsToHolder ) external override { // Validate and reduce sender approval _approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount)); __withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder); } /// @dev Helper to withdraw staked tokens function __withdraw( address _from, address _to, uint256 _amount, bool _claimRewards ) private nonReentrant returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // Checkpoint before burning if (_claimRewards) { (rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from); } else { __checkpoint([_from, address(0)]); } _burn(_from, _amount); __withdrawLogic(_to, _amount); emit Withdrawn(msg.sender, _from, _to, _amount); return (rewardTokens_, claimedAmounts_); } ///////////// // REWARDS // ///////////// // Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed. // If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract, // and can make use of __harvestRewardsLogic() if necessary // INTERNAL FUNCTIONS /// @dev Helper to add new reward tokens. Silently ignores duplicates. function __addRewardToken(address _rewardToken) internal { if (!rewardTokens.contains(_rewardToken)) { rewardTokens.push(_rewardToken); emit RewardTokenAdded(_rewardToken); } } // PRIVATE FUNCTIONS /// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values function __calcClaimableRewardForIntegralDiff( address _account, uint256 _totalHarvestIntegral, uint256 _userHarvestIntegral ) private view returns (uint256 claimableReward_) { return balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div( INTEGRAL_PRECISION ); } /// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff function __calcIntegralForBalDiff( uint256 _supply, uint256 _currentBalance, uint256 _lastCheckpointBalance ) private pure returns (uint256 integral_) { if (_supply > 0) { uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance); if (balDiff > 0) { return balDiff.mul(INTEGRAL_PRECISION).div(_supply); } } return 0; } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpoint(address[2] memory _accounts) private { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); uint256 rewardTokensLength = rewardTokens.length; for (uint256 i; i < rewardTokensLength; i++) { __updateHarvest(rewardTokens[i], _accounts, supply); } } /// @dev Helper to checkpoint harvest data for specified accounts. /// Harvests all rewards prior to checkpoint. function __checkpointAndClaim(address _account) private returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_) { // If paused, continue to checkpoint, but don't attempt to get new rewards if (!isPaused()) { __harvestRewardsLogic(); } uint256 supply = totalSupply(); rewardTokens_ = rewardTokens; claimedAmounts_ = new uint256[](rewardTokens_.length); for (uint256 i; i < rewardTokens_.length; i++) { claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply); } emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_); return (rewardTokens_, claimedAmounts_); } /// @dev Helper to update harvest data function __updateHarvest( address _rewardToken, address[2] memory _accounts, uint256 _supply ) private { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 bal = ERC20(_rewardToken).balanceOf(address(this)); uint256 integralToAdd = __calcIntegralForBalDiff( _supply, bal, totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); totalHarvestData.lastCheckpointBalance = uint128(bal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal); } for (uint256 i; i < _accounts.length; i++) { // skip address(0), passed in upon mint and burn if (_accounts[i] == address(0)) continue; UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]]; uint256 userIntegral = userHarvestData.integral; if (userIntegral < totalIntegral) { uint256 claimableReward = uint256(userHarvestData.claimableReward).add( __calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral) ); userHarvestData.claimableReward = uint128(claimableReward); userHarvestData.integral = uint128(totalIntegral); emit UserHarvestUpdated( _accounts[i], _rewardToken, totalIntegral, claimableReward ); } } } /// @dev Helper to update harvest data and claim all rewards to holder function __updateHarvestAndClaim( address _rewardToken, address _account, uint256 _supply ) private returns (uint256 claimedAmount_) { TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken]; uint256 totalIntegral = totalHarvestData.integral; uint256 integralToAdd = __calcIntegralForBalDiff( _supply, ERC20(_rewardToken).balanceOf(address(this)), totalHarvestData.lastCheckpointBalance ); if (integralToAdd > 0) { totalIntegral = totalIntegral.add(integralToAdd); totalHarvestData.integral = uint128(totalIntegral); emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral); } UserHarvestData storage userHarvestData = rewardTokenToUserToHarvestData[_rewardToken][_account]; uint256 userIntegral = userHarvestData.integral; claimedAmount_ = userHarvestData.claimableReward; if (userIntegral < totalIntegral) { userHarvestData.integral = uint128(totalIntegral); claimedAmount_ = claimedAmount_.add( __calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral) ); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_); } if (claimedAmount_ > 0) { userHarvestData.claimableReward = 0; ERC20(_rewardToken).safeTransfer(_account, claimedAmount_); emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0); } // Repeat balance lookup since the reward token could have irregular transfer behavior uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this)); if (finalBal < totalHarvestData.lastCheckpointBalance) { totalHarvestData.lastCheckpointBalance = uint128(finalBal); emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal); } return claimedAmount_; } //////////////////////////////// // REQUIRED VIRTUAL FUNCTIONS // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _onBehalf, uint256 _amount) internal virtual; /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal virtual; /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal virtual; ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token decimals /// @return decimals_ The token decimals /// @dev Implementing contracts should override to set different decimals function decimals() public view virtual override returns (uint8 decimals_) { return DEFAULT_DECIMALS; } /// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards function _transfer( address _from, address _to, uint256 _amount ) internal override nonReentrant { __checkpoint([_from, _to]); super._transfer(_from, _to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the reward token at a particular index /// @return rewardToken_ The reward token address function getRewardTokenAtIndex(uint256 _index) public view override returns (address rewardToken_) { return rewardTokens[_index]; } /// @notice Gets the count of reward tokens being harvested /// @return count_ The count function getRewardTokenCount() public view override returns (uint256 count_) { return rewardTokens.length; } /// @notice Gets all reward tokens being harvested /// @return rewardTokens_ The reward tokens function getRewardTokens() public view override returns (address[] memory rewardTokens_) { return rewardTokens; } /// @notice Gets the TotalHarvestData for a specified reward token /// @param _rewardToken The reward token /// @return totalHarvestData_ The TotalHarvestData function getTotalHarvestDataForRewardToken(address _rewardToken) public view override returns (TotalHarvestData memory totalHarvestData_) { return rewardTokenToTotalHarvestData[_rewardToken]; } /// @notice Gets the UserHarvestData for a specified account and reward token /// @param _user The account /// @param _rewardToken The reward token /// @return userHarvestData_ The UserHarvestData function getUserHarvestDataForRewardToken(address _user, address _rewardToken) public view override returns (UserHarvestData memory userHarvestData_) { return rewardTokenToUserToHarvestData[_rewardToken][_user]; } /// @notice Checks if deposits and new reward harvesting are paused /// @return isPaused_ True if paused function isPaused() public view override returns (bool isPaused_) { return paused; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./StakingWrapperBase.sol"; /// @title StakingWrapperLibBase Contract /// @author Enzyme Council <[email protected]> /// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase abstract contract StakingWrapperLibBase is StakingWrapperBase { event TokenNameSet(string name); event TokenSymbolSet(string symbol); string private tokenName; string private tokenSymbol; /// @dev Helper function to set token name function __setTokenName(string memory _name) internal { tokenName = _name; emit TokenNameSet(_name); } /// @dev Helper function to set token symbol function __setTokenSymbol(string memory _symbol) internal { tokenSymbol = _symbol; emit TokenSymbolSet(_symbol); } ///////////////////// // ERC20 OVERRIDES // ///////////////////// /// @notice Gets the token name /// @return name_ The token name /// @dev Overrides the constructor-set storage for use in proxies function name() public view override returns (string memory name_) { return tokenName; } /// @notice Gets the token symbol /// @return symbol_ The token symbol /// @dev Overrides the constructor-set storage for use in proxies function symbol() public view override returns (string memory symbol_) { return tokenSymbol; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../utils/beacon-proxy/BeaconProxyFactory.sol"; import "./ConvexCurveLpStakingWrapperLib.sol"; /// @title ConvexCurveLpStakingWrapperFactory Contract /// @author Enzyme Council <[email protected]> /// @notice A contract factory for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory { event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken); IDispatcher private immutable DISPATCHER_CONTRACT; mapping(uint256 => address) private pidToWrapper; // Handy cache for interacting contracts mapping(address => address) private wrapperToCurveLpToken; modifier onlyOwner { require(msg.sender == getOwner(), "Only the owner can call this function"); _; } constructor( address _dispatcher, address _convexBooster, address _crvToken, address _cvxToken ) public BeaconProxyFactory(address(0)) { DISPATCHER_CONTRACT = IDispatcher(_dispatcher); __setCanonicalLib( address( new ConvexCurveLpStakingWrapperLib( address(this), _convexBooster, _crvToken, _cvxToken ) ) ); } /// @notice Deploys a staking wrapper for a given Convex pool /// @param _pid The Convex Curve pool id /// @return wrapperProxy_ The staking wrapper proxy contract address function deploy(uint256 _pid) external returns (address wrapperProxy_) { require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists"); bytes memory constructData = abi.encodeWithSelector( ConvexCurveLpStakingWrapperLib.init.selector, _pid ); wrapperProxy_ = deployProxy(constructData); pidToWrapper[_pid] = wrapperProxy_; address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken(); wrapperToCurveLpToken[wrapperProxy_] = lpToken; emit WrapperDeployed(_pid, wrapperProxy_, lpToken); return wrapperProxy_; } /// @notice Pause deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to pause function pauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true); } } /// @notice Unpauses deposits and harvesting new rewards for the given wrappers /// @param _wrappers The wrappers to unpause function unpauseWrappers(address[] calldata _wrappers) external onlyOwner { for (uint256 i; i < _wrappers.length; i++) { ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false); } } //////////////////////////////////// // BEACON PROXY FACTORY OVERRIDES // //////////////////////////////////// /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view override returns (address owner_) { return DISPATCHER_CONTRACT.getOwner(); } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Gets the Curve LP token address for a given wrapper /// @param _wrapper The wrapper proxy address /// @return lpToken_ The Curve LP token address function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) { return wrapperToCurveLpToken[_wrapper]; } // PUBLIC FUNCTIONS /// @notice Gets the wrapper address for a given Convex pool /// @param _pid The Convex pool id /// @return wrapper_ The wrapper proxy address function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) { return pidToWrapper[_pid]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../interfaces/IConvexBaseRewardPool.sol"; import "../../../interfaces/IConvexBooster.sol"; import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol"; import "../StakingWrapperLibBase.sol"; /// @title ConvexCurveLpStakingWrapperLib Contract /// @author Enzyme Council <[email protected]> /// @notice A library contract for ConvexCurveLpStakingWrapper instances contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase { IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT; address private immutable CRV_TOKEN; address private immutable CVX_TOKEN; address private convexPool; uint256 private convexPoolId; address private curveLPToken; constructor( address _owner, address _convexBooster, address _crvToken, address _cvxToken ) public StakingWrapperBase(_owner, "", "") { CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster); CRV_TOKEN = _crvToken; CVX_TOKEN = _cvxToken; } /// @notice Initializes the proxy /// @param _pid The Convex pool id for which to use the proxy function init(uint256 _pid) external { // Can validate with any variable set here require(getCurveLpToken() == address(0), "init: Initialized"); IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid); // Set ERC20 info on proxy __setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name()))); __setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol()))); curveLPToken = poolInfo.lptoken; convexPool = poolInfo.crvRewards; convexPoolId = _pid; __addRewardToken(CRV_TOKEN); __addRewardToken(CVX_TOKEN); addExtraRewards(); setApprovals(); } /// @notice Adds rewards tokens that have not yet been added to the wrapper /// @dev Anybody can call, in case more pool tokens are added. /// Is called prior to every new harvest. function addExtraRewards() public { IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool()); // Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length, // but this protects against a reward token being removed that still needs to be paid out uint256 extraRewardsCount = convexPoolContract.extraRewardsLength(); for (uint256 i; i < extraRewardsCount; i++) { // __addRewardToken silently ignores duplicates __addRewardToken( IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken() ); } } /// @notice Sets necessary ERC20 approvals, as-needed function setApprovals() public { ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max); } //////////////////////////////// // STAKING WRAPPER BASE LOGIC // //////////////////////////////// /// @dev Logic to be run during a deposit, specific to the integrated protocol. /// Do not mint staking tokens, which already happens during __deposit(). function __depositLogic(address _from, uint256 _amount) internal override { ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount); CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true); } /// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol. /// Can also be used to add new rewards tokens dynamically. /// Do not checkpoint, only harvest the rewards. function __harvestRewardsLogic() internal override { // It's probably overly-cautious to check rewards on every call, // but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units, // so more convenient to always check than to monitor for rewards changes. addExtraRewards(); IConvexBaseRewardPool(getConvexPool()).getReward(); } /// @dev Logic to be run during a withdrawal, specific to the integrated protocol. /// Do not burn staking tokens, which already happens during __withdraw(). function __withdrawLogic(address _to, uint256 _amount) internal override { IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false); ERC20(getCurveLpToken()).safeTransfer(_to, _amount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the associated Convex reward pool address /// @return convexPool_ The reward pool function getConvexPool() public view returns (address convexPool_) { return convexPool; } /// @notice Gets the associated Convex reward pool id (pid) /// @return convexPoolId_ The pid function getConvexPoolId() public view returns (uint256 convexPoolId_) { return convexPoolId; } /// @notice Gets the associated Curve LP token /// @return curveLPToken_ The Curve LP token function getCurveLpToken() public view returns (address curveLPToken_) { return curveLPToken; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexBaseRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexBaseRewardPool { function extraRewards(uint256) external view returns (address); function extraRewardsLength() external view returns (uint256); function getReward() external returns (bool); function withdrawAndUnwrap(uint256, bool) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title IConvexBooster Interface /// @author Enzyme Council <[email protected]> interface IConvexBooster { struct PoolInfo { address lptoken; address token; address gauge; address crvRewards; address stash; bool shutdown; } function deposit( uint256, uint256, bool ) external returns (bool); function poolInfo(uint256) external view returns (PoolInfo memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IConvexVirtualBalanceRewardPool Interface /// @author Enzyme Council <[email protected]> interface IConvexVirtualBalanceRewardPool { function rewardToken() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IBeacon.sol"; /// @title BeaconProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract that uses the beacon pattern for instant upgrades contract BeaconProxy { address private immutable BEACON; constructor(bytes memory _constructData, address _beacon) public { BEACON = _beacon; (bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall( _constructData ); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = IBeacon(BEACON).getCanonicalLib(); assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } receive() external payable {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./BeaconProxy.sol"; import "./IBeaconProxyFactory.sol"; /// @title BeaconProxyFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Factory contract that deploys beacon proxies abstract contract BeaconProxyFactory is IBeaconProxyFactory { event CanonicalLibSet(address nextCanonicalLib); event ProxyDeployed(address indexed caller, address proxy, bytes constructData); address private canonicalLib; constructor(address _canonicalLib) public { __setCanonicalLib(_canonicalLib); } /// @notice Deploys a new proxy instance /// @param _constructData The constructor data with which to call `init()` on the deployed proxy /// @return proxy_ The proxy address function deployProxy(bytes memory _constructData) public override returns (address proxy_) { proxy_ = address(new BeaconProxy(_constructData, address(this))); emit ProxyDeployed(msg.sender, proxy_, _constructData); return proxy_; } /// @notice Gets the canonical lib used by all proxies /// @return canonicalLib_ The canonical lib function getCanonicalLib() public view override returns (address canonicalLib_) { return canonicalLib; } /// @notice Gets the contract owner /// @return owner_ The contract owner function getOwner() public view virtual returns (address owner_); /// @notice Sets the next canonical lib used by all proxies /// @param _nextCanonicalLib The next canonical lib function setCanonicalLib(address _nextCanonicalLib) public override { require( msg.sender == getOwner(), "setCanonicalLib: Only the owner can call this function" ); __setCanonicalLib(_nextCanonicalLib); } /// @dev Helper to set the next canonical lib function __setCanonicalLib(address _nextCanonicalLib) internal { canonicalLib = _nextCanonicalLib; emit CanonicalLibSet(_nextCanonicalLib); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Gets the contract owner return owner_ The contract owner
function getOwner() public view override returns (address owner_) { return DISPATCHER_CONTRACT.getOwner(); }
6,114,911
//SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {IPartCollection} from "../interfaces/IPartCollection.sol"; import {URICompiler} from "../libraries/URICompiler.sol"; import {IHost} from "../interfaces/IHost.sol"; import {IFrameCollection} from "../interfaces/IFrameCollection.sol"; import {AvatarBase} from "../libraries/AvatarBase.sol"; import {Part} from "../interfaces/IAvatar.sol"; import {IDava} from "../interfaces/IDava.sol"; import {OnchainMetadata} from "../libraries/OnchainMetadata.sol"; import {QuickSort} from "../libraries/QuickSort.sol"; contract AvatarV1 is AvatarBase { using Strings for uint256; function version() public pure override returns (string memory) { return "V1"; } function getPFP() external view override returns (string memory) { return OnchainMetadata.compileImages(_imgURIs()); } function getMetadata() external view override returns (string memory) { IDava _dava = IDava(dava()); Part[] memory parts = allParts(); IPartCollection.Attribute[] memory attributes = new IPartCollection.Attribute[](parts.length); uint256 wearingPartAmount = 0; for (uint256 i = 0; i < parts.length; i += 1) { if (parts[i].collection != address(0x0)) { attributes[wearingPartAmount] = IPartCollection.Attribute( IPartCollection(parts[i].collection).categoryTitle( parts[i].id ), IPartCollection(parts[i].collection).partTitle(parts[i].id) ); wearingPartAmount += 1; } } IPartCollection.Attribute[] memory wearingAttributes = new IPartCollection.Attribute[]( wearingPartAmount + 1 ); for (uint256 i = 0; i < wearingPartAmount; i += 1) { wearingAttributes[i] = attributes[i]; } wearingAttributes[wearingPartAmount] = IPartCollection.Attribute( "ADDRESS", uint256(uint160(address(this))).toHexString(20) ); string memory baseURI = IHost(dava()).baseURI(); string[] memory infoParams = new string[](3); infoParams[0] = "info"; infoParams[1] = uint256(uint160(address(_dava))).toHexString(20); infoParams[2] = uint256(_props().davaId).toString(); return OnchainMetadata.toMetadata( string( abi.encodePacked( "DAVA #", uint256(_props().davaId).toString() ) ), string( abi.encodePacked( "Genesis Avatar (", uint256(uint160(address(this))).toHexString(20), ")" ) ), _imgURIs(), externalImgUri(), URICompiler.getFullUri( baseURI, infoParams, new URICompiler.Query[](0) ), wearingAttributes ); } function externalImgUri() public view override returns (string memory) { IDava _dava = IDava(dava()); Part[] memory parts = allParts(); address frameCollection = _dava.frameCollection(); IFrameCollection.FrameWithUri[] memory frames = IFrameCollection( frameCollection ).getAllFrames(); QuickSort.Layer[] memory layers = new QuickSort.Layer[]( parts.length + frames.length ); URICompiler.Query[] memory queries = new URICompiler.Query[]( parts.length + frames.length ); for (uint256 i = 0; i < frames.length; i += 1) { queries[i] = URICompiler.Query( uint256(uint160(frameCollection)).toHexString(20), frames[i].id.toString() ); layers[i] = QuickSort.Layer(i, frames[i].zIndex); } uint256 layerAmount = frames.length; for (uint256 i = 0; i < parts.length; i += 1) { if (parts[i].collection != address(0x0)) { queries[layerAmount] = URICompiler.Query( uint256(uint160(parts[i].collection)).toHexString(20), uint256(parts[i].id).toString() ); layers[layerAmount] = QuickSort.Layer( layerAmount, IPartCollection(parts[i].collection).zIndex(parts[i].id) ); layerAmount += 1; } } if (layerAmount > 1) { QuickSort.sort(layers, int256(0), int256(layerAmount - 1)); } URICompiler.Query[] memory sortedQueries = new URICompiler.Query[]( layerAmount ); for (uint256 i = 0; i < layerAmount; i += 1) { sortedQueries[i] = queries[layers[i].value]; } string memory baseURI = IHost(dava()).baseURI(); string[] memory imgParams = new string[](1); imgParams[0] = "images"; return URICompiler.getFullUri(baseURI, imgParams, sortedQueries); } function _imgURIs() private view returns (string[] memory) { IDava _dava = IDava(dava()); Part[] memory parts = allParts(); address frameCollection = _dava.frameCollection(); IFrameCollection.FrameWithUri[] memory frames = IFrameCollection( frameCollection ).getAllFrames(); uint256 totalLayers = frames.length + parts.length; uint256 validLayers = frames.length; QuickSort.Layer[] memory layers = new QuickSort.Layer[](totalLayers); string[] memory imgURIs = new string[](totalLayers); for (uint256 i = 0; i < frames.length; i += 1) { imgURIs[i] = frames[i].imgUri; layers[i] = QuickSort.Layer(i, frames[i].zIndex); } for (uint256 i = 0; i < parts.length; i += 1) { if (parts[i].collection != address(0x0)) { imgURIs[validLayers] = IPartCollection(parts[i].collection) .imageUri(parts[i].id); layers[validLayers] = QuickSort.Layer( validLayers, IPartCollection(parts[i].collection).zIndex(parts[i].id) ); validLayers += 1; } } if (validLayers > 1) { QuickSort.sort(layers, int256(0), int256(validLayers - 1)); } string[] memory sortedImgURIs = new string[](validLayers); for (uint256 i = 0; i < validLayers; i += 1) { sortedImgURIs[i] = imgURIs[layers[i].value]; } return sortedImgURIs; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {IERC1155} from "@openzeppelin/contracts/interfaces/IERC1155.sol"; interface IPartCollection is IERC1155 { struct Attribute { string trait_type; string value; } function createPart( bytes32 categoryId_, string memory title_, string memory description_, string memory ipfsHash_, Attribute[] memory attributes_, uint256 maxSupply_ ) external; function createCategory( string memory title_, uint256 backgroundImageTokenId_, uint256 foregroundImageTokenId_, uint256 zIndex_ ) external; function dava() external view returns (address); function numberOfParts() external view returns (uint256); function description(uint256 tokenId) external view returns (string memory); function imageUri(uint256 tokenId_) external view returns (string memory); function zIndex(uint256 tokenId_) external view returns (uint256); function categoryInfo(bytes32 categoryId_) external view returns ( string memory name_, uint256 backgroundImgTokenId_, uint256 foregroundImgTokenId_, uint256 zIndex_ ); function categoryId(uint256 tokenId_) external view returns (bytes32); function categoryTitle(uint256 tokenId_) external view returns (string memory); function partTitle(uint256 tokenId_) external view returns (string memory); function image(uint256 tokenId_) external view returns (string memory); function maxSupply(uint256 tokenId_) external view returns (uint256); } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; library URICompiler { struct Query { string key; string value; } function getFullUri( string memory host, string[] memory params, Query[] memory queries ) internal pure returns (string memory) { string memory queryString; for (uint256 i = 0; i < params.length; i += 1) { host = string(abi.encodePacked(host, "/", params[i])); } for (uint256 i = 0; i < queries.length; i += 1) { if (i == 0) { queryString = "?"; } if (i != 0) { queryString = string(abi.encodePacked(queryString, "&")); } queryString = string( abi.encodePacked( queryString, queries[i].key, "=", queries[i].value ) ); } return string(abi.encodePacked(host, queryString)); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; interface IHost { function baseURI() external view returns (string memory); } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {IERC165} from "@openzeppelin/contracts/interfaces/IERC165.sol"; interface IFrameCollection is IERC165 { struct Frame { uint256 zIndex; string ipfsHash; } struct FrameWithUri { uint256 id; string ipfsHash; string imgUri; uint256 zIndex; } function frameOf(uint256 frameId) external view returns (FrameWithUri memory); function getAllFrames() external view returns (FrameWithUri[] memory); function totalFrames() external view returns (uint256); } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol"; import {IERC1155} from "@openzeppelin/contracts/interfaces/IERC1155.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {Account} from "./Account.sol"; import {MinimalProxy, Proxy} from "./MinimalProxy.sol"; import {IAccount} from "../interfaces/IAccount.sol"; import {IAvatar, Part} from "../interfaces/IAvatar.sol"; import {IDava} from "../interfaces/IDava.sol"; import {IPartCollection} from "../interfaces/IPartCollection.sol"; import {IFrameCollection} from "../interfaces/IFrameCollection.sol"; abstract contract AvatarBase is MinimalProxy, IAvatar, Account { using Strings for uint256; event PutOn(bytes32 indexed categoryId, address collection, uint256 id); event TakeOff(bytes32 indexed categoryId, address collection, uint256 id); // DO NOT DECLARE state variables in the proxy contract. // If you wanna access to the existing state variables, use _props(). // If you want to add new variables, design a new struct and allocate a slot for it. modifier onlyOwnerOrDava() { require( msg.sender == owner() || msg.sender == dava(), "Avatar: only owner or Dava can call this" ); _; } receive() external payable override(Proxy, Account) {} function dress(Part[] calldata partsOn, bytes32[] calldata partsOff) external virtual override onlyOwnerOrDava { for (uint256 i = 0; i < partsOff.length; i += 1) { _takeOff(partsOff[i]); } for (uint256 i = 0; i < partsOn.length; i += 1) { _putOn(partsOn[i]); } } function owner() public view override returns (address) { return IDava(dava()).ownerOf(_props().davaId); } function dava() public view override returns (address) { return StorageSlot.getAddressSlot(DAVA_CONTRACT_SLOT).value; } function davaId() public view override returns (uint256) { return _props().davaId; } function part(bytes32 categoryId) public view override returns (Part memory) { // Try to retrieve from the storage Part memory part_ = _props().parts[categoryId]; if (part_.collection == address(0x0)) { return Part(address(0x0), 0); } // Check the balance bool owning = _isEligible(part_); // return the part only when the Avatar owns the part or return a null part. if (owning) { return part_; } else { return Part(address(0x0), 0); } } function allParts() public view virtual override returns (Part[] memory parts) { IDava _dava = IDava(dava()); bytes32[] memory allCategories = _dava.getAllSupportedCategories(); parts = new Part[](allCategories.length); for (uint256 i = 0; i < allCategories.length; i += 1) { parts[i] = part(allCategories[i]); } } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAvatar).interfaceId || super.supportsInterface(interfaceId); } function version() public pure virtual override returns (string memory); function getPFP() external view virtual override returns (string memory); function getMetadata() external view virtual override returns (string memory); function _putOn(Part memory part_) internal { bytes32 categoryId = IPartCollection(part_.collection).categoryId( part_.id ); _props().parts[categoryId] = part_; emit PutOn(categoryId, part_.collection, part_.id); } function _takeOff(bytes32 categoryId) internal { Part memory target = _props().parts[categoryId]; delete _props().parts[categoryId]; emit TakeOff(categoryId, target.collection, target.id); } function _isEligible(Part memory part_) internal view virtual returns (bool) { require( IDava(dava()).isDavaPart( part_.collection, IPartCollection(part_.collection).categoryId(part_.id) ), "Avatar: not a registered part." ); return (IERC1155(part_.collection).balanceOf(address(this), part_.id) > 0); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; struct Part { address collection; uint96 id; } interface IAvatar { function dress(Part[] calldata partsOn, bytes32[] calldata partsOff) external; function version() external view returns (string memory); function dava() external view returns (address); function davaId() external view returns (uint256); function part(bytes32 categoryId) external view returns (Part memory); function allParts() external view returns (Part[] memory parts); function getPFP() external view returns (string memory); function getMetadata() external view returns (string memory); function externalImgUri() external view returns (string memory); } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {IERC721} from "@openzeppelin/contracts/interfaces/IERC721.sol"; import {IHost} from "../interfaces/IHost.sol"; import {Part} from "../interfaces/IAvatar.sol"; interface IDava is IERC721, IHost { function mint(address to, uint256 id) external returns (address); function registerCollection(address collection) external; function registerCategory(bytes32 categoryId) external; function registerFrameCollection(address collection) external; function deregisterCollection(address collection) external; function deregisterCategory(bytes32 categoryId) external; function zap( uint256 tokenId, Part[] calldata partsOn, bytes32[] calldata partsOff ) external; function frameCollection() external view returns (address); function isRegisteredCollection(address collection) external view returns (bool); function isSupportedCategory(bytes32 categoryId) external view returns (bool); function isDavaPart(address collection, bytes32 categoryId) external view returns (bool); function getAvatar(uint256 id) external view returns (address); function getAllSupportedCategories() external view returns (bytes32[] memory); function getRegisteredCollections() external view returns (address[] memory); function getPFP(uint256 id) external view returns (string memory); } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {IPartCollection} from "../interfaces/IPartCollection.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; library OnchainMetadata { using Strings for uint256; string private constant SVG_START_LINE = "<svg xmlns='http://www.w3.org/2000/svg' width='1000' height='1000' viewBox='0 0 1000 1000'>"; string private constant SVG_END_LINE = "</svg>"; string private constant SVG_IMG_START_LINE = "<image href='"; string private constant SVG_IMG_END_LINE = "' width='100%'/>"; function toMetadata( string memory name, string memory description, string[] memory imgURIs, string memory externalImgUri, string memory externalUri, IPartCollection.Attribute[] memory attributes ) internal pure returns (string memory) { bytes memory metadata = abi.encodePacked( 'data:application/json;utf8,{"name":"', name, '","external_url":"', externalUri, '","description":"', description, '","attributes":[' ); for (uint256 i = 0; i < attributes.length; i += 1) { IPartCollection.Attribute memory attribute = attributes[i]; metadata = abi.encodePacked( metadata, '{"trait_type":"', attribute.trait_type, '","value":"', attribute.value, '"}' ); if (i < attributes.length - 1) { metadata = abi.encodePacked(metadata, ","); } } metadata = abi.encodePacked( metadata, '],"raw_image":"data:image/svg+xml;utf8,', compileImages(imgURIs), '","image":"', externalImgUri, '"}' ); return string(metadata); } function compileImages(string[] memory imgURIs) internal pure returns (string memory) { string memory accumulator; for (uint256 i = 0; i < imgURIs.length; i += 1) { accumulator = string( abi.encodePacked(accumulator, toSVGImage(imgURIs[i])) ); } return string(abi.encodePacked(SVG_START_LINE, accumulator, SVG_END_LINE)); } function toSVGImage(string memory imgUri) internal pure returns (string memory) { return string( abi.encodePacked(SVG_IMG_START_LINE, imgUri, SVG_IMG_END_LINE) ); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; /// @title QuickSort /// @notice basic quickSort function from https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f#file-quicksort-sol library QuickSort { struct Layer { uint256 value; uint256 index; } function sort( Layer[] memory arr, int256 left, int256 right ) internal pure { int256 i = left; int256 j = right; if (i == j) return; uint256 pivot = arr[uint256(left + (right - left) / 2)].index; while (i <= j) { while (arr[uint256(i)].index < pivot) i += 1; while (pivot < arr[uint256(j)].index) j -= 1; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = ( arr[uint256(j)], arr[uint256(i)] ); i += 1; j -= 1; } } if (left < j) sort(arr, left, j); if (i < right) sort(arr, i, right); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC1155/IERC1155.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import {ERC1155Holder, ERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import {IERC721Receiver} from "@openzeppelin/contracts/interfaces/IERC721Receiver.sol"; import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; import {Transaction, IAccount} from "../interfaces/IAccount.sol"; abstract contract Account is IAccount, IERC1271, Context, ERC721Holder, ERC1155Holder { using ECDSA for bytes32; event Executed(address to, uint256 value, bytes data); constructor() {} receive() external payable virtual {} modifier onlyOwner() { require( owner() == _msgSender() || address(this) == _msgSender(), "Account: only owner can call" ); _; } function execute(Transaction calldata transaction) public payable virtual override onlyOwner { _call(transaction); } function batchExecute(Transaction[] calldata transactions) public payable virtual override onlyOwner { for (uint256 i = 0; i < transactions.length; i += 1) { _call(transactions[i]); } } function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4 magicValue) { return (owner() == hash.recover(signature)) ? IERC1271.isValidSignature.selector : bytes4(0xffffffff); } function owner() public view virtual override returns (address); function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC1271).interfaceId || interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IAccount).interfaceId || super.supportsInterface(interfaceId); } function _call(Transaction memory transaction) internal { (bool success, ) = transaction.to.call{value: transaction.value}( transaction.data ); require(success, "Account: transaction reverted"); emit Executed(transaction.to, transaction.value, transaction.data); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol"; import {Proxy} from "@openzeppelin/contracts/proxy/Proxy.sol"; import {IBeacon} from "@openzeppelin/contracts/proxy/beacon/IBeacon.sol"; import {ERC1967Upgrade} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol"; import {Part} from "../interfaces/IAvatar.sol"; struct Props { uint256 davaId; mapping(bytes32 => Part) parts; } contract MinimalProxy is Initializable, Proxy, ERC1967Upgrade { bytes32 internal constant DAVA_CONTRACT_SLOT = bytes32(uint256(keccak256("dava.contract")) - 1); bytes32 internal constant PROPS_SLOT = bytes32(uint256(keccak256("dava.props.v1")) - 1); function initialize(uint256 davaId_) public virtual initializer { _upgradeBeaconToAndCall(msg.sender, "", false); StorageSlot.getAddressSlot(DAVA_CONTRACT_SLOT).value = msg.sender; _props().davaId = davaId_; } function _props() internal pure virtual returns (Props storage r) { bytes32 slot = PROPS_SLOT; assembly { r.slot := slot } } // See openzeppelin's BeaconProxy.sol function _beacon() internal view virtual returns (address) { return _getBeacon(); } function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } //SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; pragma abicoder v2; struct Transaction { address to; uint256 value; bytes data; } interface IAccount { function execute(Transaction calldata transaction) external payable; function batchExecute(Transaction[] calldata transactions) external payable; function owner() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721Receiver.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
Try to retrieve from the storage return the part only when the Avatar owns the part or return a null part.
function part(bytes32 categoryId) public view override returns (Part memory) { Part memory part_ = _props().parts[categoryId]; if (part_.collection == address(0x0)) { return Part(address(0x0), 0); } if (owning) { return part_; return Part(address(0x0), 0); } }
6,147,634
./full_match/80001/0x72C87B8B8afD695513C45601983647931f4Caa28/sources/contracts/DAO/SharedAddress/SharedAddress.sol
Initialize the TaskDisputes plugin. _dao The dao where this plugin is installed. _hats The deployment of Hats Protocol to use.
function initialize(IDAO _dao, IHats _hats) external initializer { __PluginUUPSUpgradeable_init(_dao); hats = _hats; }
862,460
./full_match/5/0xC90e6D2da093369EC01815372490F12CE75F116c/sources/project_/contracts/RootBrsBridge.sol
l1 -> l2 브릿지로 brs를 보냅니다. bytes memory data = "0x00";
function sendToBridge( address account, uint256 amount ) public onlyOwner brsCheck(amount) { require( brsToken.allowance(address(this), address(bridge)) >= amount, "BRS: Insufficient amount of approver." ); emit SendToBridgeEvent(account, amount); bridge.deposit(address(brsToken), account, amount, "0x00"); }
1,886,914
//SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IOptions.sol"; import "./interfaces/IUniOption.sol"; /** * @author [email protected] * @title Option factory aka Mighty Option Chef * @notice Option Chef has the monopoly to mint and destroy NFT UniOptions */ contract OptionChef is Ownable { //storage IHegicOptions public hegicOption; IUniOption public uniOption; //ideally this should've been a mapping/arr of id->Struct {owner, id} //there are a few EVM gotchas for this (afaik one can't peek into //mapped structs from another contracts, happy to restructure if I'm wrong though) uint256[] uIds; uint256[] ids; //events event Wrapped(address account, uint optionId); event Unwrapped(address account, uint tokenId); //utility functions function updateHegicOption(IHegicOptions _hegicOption) external onlyOwner { hegicOption = _hegicOption ; } function updateUniOption(IUniOption _uniOption) external onlyOwner { uniOption = _uniOption; } constructor(IHegicOptions _hegicOption) public { hegicOption = _hegicOption ; } //core (un)wrap functionality /** * @notice UniOption wrapper adapter for Hegic */ function wrapHegic(uint _uId) public returns (uint newTokenId) { require(ids[_uId] == 0 , "UOPT:exists"); (, address holder, , , , , , ) = hegicOption.options(_uId); //auth is a bit unintuitive for wrapping, see NFT.sol:isApprovedOrOwner() require(holder == msg.sender, "UOPT:ownership"); newTokenId = uniOption.mintUniOption(msg.sender); uIds[newTokenId] = _uId; ids[_uId] = newTokenId; emit Wrapped(msg.sender, _uId); } /** * @notice UniOption unwrapper adapter for Hegic * @notice check burning logic, do we really want to burn it (vs meta) * @notice TODO recheck escrow mechanism on 0x relay to prevent unwrapping when locked */ function unwrapHegic(uint _tokenId) external onlyTokenOwner(_tokenId) { // checks if hegicOption will allow to transfer option ownership (IHegicOptions.State state, , , , , , uint expiration , ) = getUnderlyingOptionParams(_tokenId); if (state == IHegicOptions.State.Active || expiration >= block.timestamp) { hegicOption.transfer(uIds[_tokenId], msg.sender); } //burns anyway if token is expired uniOption.burnUniOption(_tokenId); ids[uIds[_tokenId]] = 0; uIds[_tokenId] = 0; emit Unwrapped(msg.sender, _tokenId); } function getUnderlyingOptionId(uint _tokenId) external view returns (uint) { return uIds[_tokenId]; } function getUnderlyingOptionParams(uint _tokenId) public view returns ( IHegicOptions.State state, address payable holder, uint256 strike, uint256 amount, uint256 lockedAmount, uint256 premium, uint256 expiration, IHegicOptions.OptionType optionType) { (state, holder, strike, amount, lockedAmount, premium, expiration, optionType) = hegicOption.options(uIds[_tokenId]); } /** * @notice check whether Chef has underlying option locked */ function isDelegated(uint _tokenId) public view returns (bool) { ( , address holder, , , , , , ) = hegicOption.options(uIds[_tokenId]); return holder == address(this); } function createHegic( uint _period, uint _amount, uint _strike, IHegicOptions.OptionType _optionType ) payable external returns (uint) { uint optionId = hegicOption.create{value: msg.value}(_period, _amount, _strike, _optionType); // return eth excess payable(msg.sender).transfer(address(this).balance); return wrapHegic(optionId); } modifier onlyTokenOwner(uint _itemId) { require(msg.sender == uniOption.ownerOf(_itemId), "UOPT:ownership/exchange"); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IHegicOptions { event Create( uint256 indexed id, address indexed account, uint256 settlementFee, uint256 totalFee ); event Exercise(uint256 indexed id, uint256 profit); event Expire(uint256 indexed id, uint256 premium); enum State {Inactive, Active, Exercised, Expired} enum OptionType {Invalid, Put, Call} struct Option { State state; address payable holder; uint256 strike; uint256 amount; uint256 lockedAmount; uint256 premium; uint256 expiration; OptionType optionType; } function create( uint256 period, uint256 amount, uint256 strike, OptionType optionType ) external payable returns (uint256 optionID); function transfer(uint256 optionID, address payable newHolder) external; function exercise(uint256 optionID) external; function options(uint) external view returns ( State state, address payable holder, uint256 strike, uint256 amount, uint256 lockedAmount, uint256 premium, uint256 expiration, OptionType optionType ); function unlock(uint256 optionID) external; } interface IHegicETHOptions is IHegicOptions { function fees( uint256 period, uint256 amount, uint256 strike, OptionType optionType ) external view returns ( uint256 total, uint256 settlementFee, uint256 strikeFee, uint256 periodFee ); } interface IHegicERC20Options is IHegicOptions { function fees( uint256 period, uint256 amount, uint256 strike, OptionType optionType ) external view returns ( uint256 total, uint256 totalETH, uint256 settlementFee, uint256 strikeFee, uint256 periodFee ); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IUniOption { //custom functions in use function burnUniOption(uint _id) external; function mintUniOption(address _to) external returns (uint256); //IERC721 functions in use function ownerOf(uint256 tokenId) external view returns (address owner); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
SPDX-License-Identifier: UNLICENSEDcustom functions in useIERC721 functions in use
interface IUniOption { function burnUniOption(uint _id) external; function mintUniOption(address _to) external returns (uint256); function ownerOf(uint256 tokenId) external view returns (address owner); }
9,960,795
/** * This smart contract code is Copyright 2018 TokenMarket Ltd. For more information see https://tokenmarket.net * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * NatSpec is used intentionally to cover also other than public functions * Solidity 0.4.18 is intentionally used: it's stable, and our framework is * based on that. */ pragma solidity ^0.4.18; import "../CrowdsaleToken.sol"; import "../Recoverable.sol"; import "./CheckpointToken.sol"; import "./ERC865.sol"; import "zeppelin/contracts/math/SafeMath.sol"; import "zeppelin/contracts/ownership/Whitelist.sol"; import "zeppelin/contracts/ownership/rbac/RBAC.sol"; /** * @dev Interface for general announcements about the security. * * Announcements can be for instance for dividend sharing, voting, or * just for general announcements. */ interface Announcement { function announcementName() public view returns (bytes32); function announcementURI() public view returns (bytes32); function announcementType() public view returns (uint256); function announcementHash() public view returns (uint256); } /** * @author TokenMarket / Ville Sundell <ville at tokenmarket.net> */ contract SecurityToken is CheckpointToken, RBAC, Recoverable, ERC865 { using SafeMath for uint256; // We use only uint256 for safety reasons (no boxing) string constant ROLE_ANNOUNCE = "announce()"; string constant ROLE_FORCE = "forceTransfer()"; string constant ROLE_ISSUE = "issueTokens()"; string constant ROLE_BURN = "burnTokens()"; string constant ROLE_INFO = "setTokenInformation()"; string constant ROLE_SETVERIFIER = "setTransactionVerifier()"; /// @dev Version string telling the token is TM-01, and its version: string public version = 'TM-01 0.1'; /// @dev URL where you can get more information about the security /// (for example company website or investor interface): string public url; /** SecurityToken specific events **/ /// @dev This is emitted when new tokens are created: event Issued(address indexed to, uint256 value); /// @dev This is emitted when tokens are burned from token's own stash: event Burned(address indexed burner, uint256 value); /// @dev This is emitted upon forceful transfer of tokens by the Board: event Forced(address indexed from, address indexed to, uint256 value); /// @dev This is emitted when new announcements (like dividends, voting, etc.) are issued by the Board: event Announced(address indexed announcement, uint256 indexed announcementType, bytes32 indexed announcementName, bytes32 announcementURI, uint256 announcementHash); /// @dev This is emitted when token information is changed: event UpdatedTokenInformation(string newName, string newSymbol, string newUrl); /// @dev This is emitted when transaction verifier (the contract which would check KYC, etc.): event UpdatedTransactionVerifier(address newVerifier); /// @dev Address list of Announcements (see "interface Announcement"). /// Announcements are things like votings, dividends, or any kind of /// smart contract: address[] public announcements; /// @dev For performance reasons, we also maintain address based mapping of /// Announcements: mapping(address => uint256) public announcementsByAddress; /** * @dev Contructor to create SecurityToken, and subsequent CheckpointToken. * * CheckpointToken will be created with hardcoded 18 decimals. * * @param _name Initial name of the token * @param _symbol Initial symbol of the token */ function SecurityToken(string _name, string _symbol, string _url) CheckpointToken(_name, _symbol, 18) public { url = _url; addRole(msg.sender, ROLE_ANNOUNCE); addRole(msg.sender, ROLE_FORCE); addRole(msg.sender, ROLE_ISSUE); addRole(msg.sender, ROLE_BURN); addRole(msg.sender, ROLE_INFO); addRole(msg.sender, ROLE_SETVERIFIER); } /** * @dev Function to announce Announcements. * * Announcements can be for instance for dividend sharing, voting, or * just for general announcements. * * Instead of storing the announcement details, we just broadcast them as an * event, and store only the address. * * @param announcement Address of the Announcement */ function announce(Announcement announcement) external onlyRole(ROLE_ANNOUNCE) { announcements.push(announcement); announcementsByAddress[address(announcement)] = announcements.length; Announced(address(announcement), announcement.announcementType(), announcement.announcementName(), announcement.announcementURI(), announcement.announcementHash()); } /** * @dev Function to forcefully transfer tokens from A to B by board decission * * This must be implemented carefully, since this is a very critical part * to ensure investor safety. * * This is intended to be called by the BAC (The Board), hence the whitelisting. * * @param from Address of the account to confisticate the tokens from * @param to Address to deposit the confisticated token to * @param value amount of tokens to be confisticated */ function forceTransfer(address from, address to, uint256 value) external onlyRole(ROLE_FORCE) { transferInternal(from, to, value); Forced(from, to, value); } /** * @dev Issue new tokens to the board by a board decission * * Issue new tokens. This is intended to be called by the BAC (The Board), * hence the whitelisting. * * @param value Token amount to issue */ function issueTokens(uint256 value) external onlyRole(ROLE_ISSUE) { address issuer = msg.sender; uint256 blackHoleBalance = balanceOf(address(0)); uint256 totalSupplyNow = totalSupply(); setCheckpoint(tokenBalances[address(0)], blackHoleBalance.add(value)); transferInternal(address(0), issuer, value); setCheckpoint(tokensTotal, totalSupplyNow.add(value)); Issued(issuer, value); } /** * @dev Burn tokens from contract's own balance by a board decission * * Burn tokens from contract's own balance to prevent accidental burnings. * This is intended to be called by the BAC (The Board), hence the whitelisting. * * @param value Token amount to burn from this contract's balance */ function burnTokens(uint256 value) external onlyRole(ROLE_BURN) { address burner = address(this); uint256 burnerBalance = balanceOf(burner); uint256 totalSupplyNow = totalSupply(); transferInternal(burner, address(0), value); setCheckpoint(tokenBalances[address(0)], burnerBalance.sub(value)); setCheckpoint(tokensTotal, totalSupplyNow.sub(value)); Burned(burner, value); } /** * @dev Whitelisted users (The Board, BAC) can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. * * @param _name New name of the token * @param _symbol New symbol of the token * @param _url New URL of the token */ function setTokenInformation(string _name, string _symbol, string _url) external onlyRole(ROLE_INFO) { name = _name; symbol = _symbol; url = _url; UpdatedTokenInformation(name, symbol, url); } /** * @dev Set transaction verifier * * This sets a SecurityTransferAgent to be used as a transaction verifier for * each transfer. This is implemented for possible regulatory requirements. * * @param newVerifier Address of the SecurityTransferAgent used as verifier */ function setTransactionVerifier(SecurityTransferAgent newVerifier) external onlyRole(ROLE_SETVERIFIER) { transferVerifier = newVerifier; UpdatedTransactionVerifier(newVerifier); } }
Function to forcefully transfer tokens from A to B by board decission This must be implemented carefully, since this is a very critical part to ensure investor safety. This is intended to be called by the BAC (The Board), hence the whitelisting. from Address of the account to confisticate the tokens from to Address to deposit the confisticated token to value amount of tokens to be confisticated/
function forceTransfer(address from, address to, uint256 value) external onlyRole(ROLE_FORCE) { transferInternal(from, to, value); Forced(from, to, value); }
12,735,647
./full_match/1/0x8b909aC9F3cba71d7A0B72397Ec82A74D2aC8D0F/sources/contracts/Coupon/Coupon.sol
Current rebate amount for new, mintable token. Based on CryptOrchids current price, the ramping rebate is intended to address the regrettable FOMO ramp pricing. Starts at 0.02ETH, and increases with inverse correlation to price ramp to offer effectively straight 0.04 ETH for seeds. calls CryptOrchids.currentPrice and finds difference with MINT_FLOOR to return rebate./
function setCurrentRebate() public { uint256 currentPrice = ERC721(cryptorchidsERC721).currentPrice(); if (currentPrice == MINT_FLOOR) { currentRebate = REBATE_AMOUNT; return; } currentRebate = currentPrice - MINT_FLOOR; }
4,907,880
/** *Submitted for verification at Etherscan.io on 2021-03-16 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File: contracts/Constants.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 84; /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e22; // 10,000 VSD address private constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant CURRENT_EPOCH_OFFSET = 0; uint256 private constant CURRENT_EPOCH_START = 1612324800; uint256 private constant CURRENT_EPOCH_PERIOD = 28800; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 9; // 9 epochs uint256 private constant GOVERNANCE_EXPIRATION = 8; // 2 + 1 epochs uint256 private constant GOVERNANCE_QUORUM = 10e16; // 10% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE = 1e20; // 100 VSD uint256 private constant EXPANSION_ADVANCE_INCENTIVE = 3e20; // 300 VSD uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 15; // 15 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 30; // 10 days uint256 private constant DEBT_RATIO_CAP = 15e16; // 15% /* Regulator */ uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 6e16; // 6% uint256 private constant SUPPLY_INCREASE_FUND_RATIO = 1500; // 15% uint256 private constant SUPPLY_INCREASE_PRICE_THRESHOLD = 105e16; // 1.05 uint256 private constant SUPPLY_INCREASE_PRICE_TARGET = 1045e15; // 1.045 uint256 private constant SUPPLY_DECREASE_PRICE_THRESHOLD = 95e16; // 0.95 uint256 private constant SUPPLY_DECREASE_PRICE_TARGET = 95e16; // 0.95 /* Collateral */ uint256 private constant REDEMPTION_RATE = 9500; // 95% uint256 private constant FUND_DEV_PCT = 70; // 70% uint256 private constant COLLATERAL_RATIO = 9000; // 90% /* Deployed */ address private constant TREASURY_ADDRESS = address(0x3a640b96405eCB10782C130022e1E5a560EBcf11); address private constant DEV_ADDRESS = address(0x5bC47D40F69962d1a9Db65aC88f4b83537AF5Dc2); address private constant MINTER_ADDRESS = address(0x6Ff1DbcF2996D8960E24F16C193EA42853995d32); address private constant GOVERNOR = address(0xB64A5630283CCBe0C3cbF887a9f7B9154aEf38c3); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getDaiAddress() internal pure returns (address) { return DAI; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getCurrentEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: CURRENT_EPOCH_OFFSET, start: CURRENT_EPOCH_START, period: CURRENT_EPOCH_PERIOD }); } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceExpiration() internal pure returns (uint256) { return GOVERNANCE_EXPIRATION; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_QUORUM}); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_PROPOSAL_THRESHOLD}); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: GOVERNANCE_SUPER_MAJORITY}); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentive() internal pure returns (uint256) { return ADVANCE_INCENTIVE; } function getExpansionAdvanceIncentive() internal pure returns (uint256) { return EXPANSION_ADVANCE_INCENTIVE; } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: DEBT_RATIO_CAP}); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: COUPON_SUPPLY_CHANGE_LIMIT}); } function getSupplyIncreaseFundRatio() internal pure returns (uint256) { return SUPPLY_INCREASE_FUND_RATIO; } function getSupplyIncreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_THRESHOLD; } function getSupplyIncreasePriceTarget() internal pure returns (uint256) { return SUPPLY_INCREASE_PRICE_TARGET; } function getSupplyDecreasePriceThreshold() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_THRESHOLD; } function getSupplyDecreasePriceTarget() internal pure returns (uint256) { return SUPPLY_DECREASE_PRICE_TARGET; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } function getDevAddress() internal pure returns (address) { return DEV_ADDRESS; } function getMinterAddress() internal pure returns (address) { return MINTER_ADDRESS; } function getFundDevPct() internal pure returns (uint256) { return FUND_DEV_PCT; } function getRedemptionRate() internal pure returns (uint256) { return REDEMPTION_RATE; } function getGovernor() internal pure returns (address) { return GOVERNOR; } function getCollateralRatio() internal pure returns (uint256) { return COLLATERAL_RATIO; } } // File: contracts/dao/Curve.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Curve { using SafeMath for uint256; using Decimal for Decimal.D256; function calculateCouponPremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) internal pure returns (uint256) { return effectivePremium(totalSupply, totalDebt, amount).mul(amount).asUint256(); } function effectivePremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) private pure returns (Decimal.D256 memory) { Decimal.D256 memory debtRatio = Decimal.ratio(totalDebt, totalSupply); Decimal.D256 memory debtRatioUpperBound = Constants.getDebtRatioCap(); uint256 totalSupplyEnd = totalSupply.sub(amount); uint256 totalDebtEnd = totalDebt.sub(amount); Decimal.D256 memory debtRatioEnd = Decimal.ratio(totalDebtEnd, totalSupplyEnd); if (debtRatio.greaterThan(debtRatioUpperBound)) { if (debtRatioEnd.greaterThan(debtRatioUpperBound)) { return curve(debtRatioUpperBound); } Decimal.D256 memory premiumCurve = curveMean(debtRatioEnd, debtRatioUpperBound); Decimal.D256 memory premiumCurveDelta = debtRatioUpperBound.sub(debtRatioEnd); Decimal.D256 memory premiumFlat = curve(debtRatioUpperBound); Decimal.D256 memory premiumFlatDelta = debtRatio.sub(debtRatioUpperBound); return (premiumCurve.mul(premiumCurveDelta)).add(premiumFlat.mul(premiumFlatDelta)) .div(premiumCurveDelta.add(premiumFlatDelta)); } return curveMean(debtRatioEnd, debtRatio); } // 1/((1-R)^2)-1 function curve(Decimal.D256 memory debtRatio) private pure returns (Decimal.D256 memory) { return Decimal.one().div( (Decimal.one().sub(debtRatio)).pow(2) ).sub(Decimal.one()); } // 1/((1-R)(1-R'))-1 function curveMean( Decimal.D256 memory lower, Decimal.D256 memory upper ) private pure returns (Decimal.D256 memory) { if (lower.equals(upper)) { return curve(lower); } return Decimal.one().div( (Decimal.one().sub(upper)).mul(Decimal.one().sub(lower)) ).sub(Decimal.one()); } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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); } // File: contracts/token/IDollar.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IDollar is IERC20 { function burn(uint256 amount) public; function burnFrom(address account, uint256 amount) public; function mint(address account, uint256 amount) public returns (bool); } // File: contracts/oracle/IOracle.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract IOracle { function capture() public returns (Decimal.D256 memory, bool); } // File: contracts/dao/State.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Account { enum Status { Frozen, Fluid, Locked } struct State { uint256 lockedUntil; mapping(uint256 => uint256) coupons; mapping(address => uint256) couponAllowances; } struct PoolState { uint256 staged; uint256 bonded; uint256 fluidUntil; uint256 rewardDebt; uint256 shareDebt; } } contract Epoch { struct Global { uint256 start; uint256 period; uint256 current; } struct Coupons { uint256 outstanding; uint256 couponRedeemed; uint256 vsdRedeemable; } struct State { uint256 totalDollarSupply; Coupons coupons; } } contract Candidate { enum Vote { UNDECIDED, APPROVE, REJECT } struct VoteInfo { Vote vote; uint256 bondedVotes; } struct State { uint256 start; uint256 period; uint256 approve; uint256 reject; mapping(address => VoteInfo) votes; bool initialized; } } contract Storage { struct Provider { IDollar dollar; IOracle oracle; } struct Balance { uint256 redeemable; uint256 clippable; uint256 debt; uint256 coupons; } struct PoolInfo { uint256 bonded; uint256 staged; mapping (address => Account.PoolState) accounts; uint256 accDollarPerLP; // Accumulated dollar per LP token, times 1e18. uint256 accSharePerLP; // Accumulated share per LP token, times 1e18. uint256 allocPoint; uint256 flags; } struct State { Epoch.Global epoch; Balance balance; Provider provider; /* * Global state variable */ uint256 totalAllocPoint; uint256 collateralRatio; mapping(uint256 => Epoch.State) epochs; mapping(uint256 => Candidate.State) candidates; mapping(address => Account.State) accounts; mapping(address => PoolInfo) pools; address[] poolList; address[] collateralAssetList; } } contract State { Storage.State _state; } // File: @uniswap/lib/contracts/libraries/Babylonian.sol pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File: contracts/dao/Getters.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Getters is State { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * ERC20 (only for snapshot voting) */ function name() public view returns (string memory) { return "Value Set Dollar Stake"; } function symbol() public view returns (string memory) { return "VSDS"; } function decimals() public view returns (uint8) { return 18; } function balanceOf(address account) public view returns (uint256) { return balanceOfBondedDollar(account); } function totalSupply() public view returns (uint256) { return totalBondedDollar(); } function allowance(address owner, address spender) external view returns (uint256) { return 0; } /** * Global */ function dollar() public view returns (IDollar) { return _state.provider.dollar; } function oracle() public view returns (IOracle) { return _state.provider.oracle; } function usdc() public view returns (address) { return Constants.getUsdcAddress(); } function dai() public view returns (address) { return Constants.getDaiAddress(); } function totalBonded(address pool) public view returns (uint256) { return _state.pools[pool].bonded; } function totalStaged(address pool) public view returns (uint256) { return _state.pools[pool].staged; } function totalDebt() public view returns (uint256) { return _state.balance.debt; } function totalRedeemable() public view returns (uint256) { return _state.balance.redeemable; } function totalClippable() public view returns (uint256) { return _state.balance.clippable; } function totalCoupons() public view returns (uint256) { return _state.balance.coupons; } function totalNet() public view returns (uint256) { return dollar().totalSupply().sub(totalDebt()); } function totalBondedDollar() public view returns (uint256) { uint256 len = _state.poolList.length; uint256 bondedDollar = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; uint256 bondedLP = totalBonded(pool); if (bondedLP == 0) { continue; } (uint256 poolBonded, ) = _getDollarReserve(pool, bondedLP); bondedDollar = bondedDollar.add(poolBonded); } return bondedDollar; } /** * Account */ function balanceOfStaged(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].staged; } function balanceOfBonded(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].bonded; } function balanceOfBondedDollar(address account) public view returns (uint256) { uint256 len = _state.poolList.length; uint256 bondedDollar = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; uint256 bondedLP = balanceOfBonded(pool, account); if (bondedLP == 0) { continue; } (uint256 reserve, ) = _getDollarReserve(pool, bondedLP); bondedDollar = bondedDollar.add(reserve); } return bondedDollar; } function balanceOfCoupons(address account, uint256 epoch) public view returns (uint256) { if (outstandingCoupons(epoch) == 0) { return 0; } return _state.accounts[account].coupons[epoch]; } function balanceOfClippable(address account, uint256 epoch) public view returns (uint256) { if (redeemableVSDs(epoch) == 0) { return 0; } return _state.accounts[account].coupons[epoch].mul(redeemableVSDs(epoch)).div(redeemedCoupons(epoch)); } function statusOf(address pool, address account) public view returns (Account.Status) { if (_state.accounts[account].lockedUntil > epoch()) { return Account.Status.Locked; } return epoch() >= _state.pools[pool].accounts[account].fluidUntil ? Account.Status.Frozen : Account.Status.Fluid; } function fluidUntil(address pool, address account) public view returns (uint256) { return _state.pools[pool].accounts[account].fluidUntil; } function lockedUntil(address account) public view returns (uint256) { return _state.accounts[account].lockedUntil; } function allowanceCoupons(address owner, address spender) public view returns (uint256) { return _state.accounts[owner].couponAllowances[spender]; } function pendingReward(address pool) public view returns (uint256 pending) { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; if (user.bonded > 0) { pending = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18).sub(user.rewardDebt); } } /** * Epoch */ function epoch() public view returns (uint256) { return _state.epoch.current; } function epochTime() public view returns (uint256) { Constants.EpochStrategy memory current = Constants.getCurrentEpochStrategy(); return epochTimeWithStrategy(current); } function epochTimeWithStrategy(Constants.EpochStrategy memory strategy) private view returns (uint256) { return blockTimestamp() .sub(strategy.start) .div(strategy.period) .add(strategy.offset); } // Overridable for testing function blockTimestamp() internal view returns (uint256) { return block.timestamp; } function outstandingCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.outstanding; } function redeemedCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.couponRedeemed; } function redeemableVSDs(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.vsdRedeemable; } function bootstrappingAt(uint256 epoch) public view returns (bool) { return epoch <= Constants.getBootstrappingPeriod(); } function totalDollarSupplyAt(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].totalDollarSupply; } /** * Governance */ function recordedVoteInfo(address account, uint256 candidate) public view returns (Candidate.VoteInfo memory) { return _state.candidates[candidate].votes[account]; } function startFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].start; } function periodFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].period; } function approveFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].approve; } function rejectFor(uint256 candidate) public view returns (uint256) { return _state.candidates[candidate].reject; } function votesFor(uint256 candidate) public view returns (uint256) { return approveFor(candidate).add(rejectFor(candidate)); } function isNominated(uint256 candidate) public view returns (bool) { return _state.candidates[candidate].start > 0; } function isInitialized(uint256 candidate) public view returns (bool) { return _state.candidates[candidate].initialized; } function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * Collateral */ function _getDollarReserve(address pool, uint256 bonded) internal view returns (uint256 reserve, uint256 totalReserve) { (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pool).getReserves(); if (IUniswapV2Pair(pool).token0() == address(dollar())) { totalReserve = reserve0; } else { require(IUniswapV2Pair(pool).token1() == address(dollar()), "the pool does not contain dollar"); totalReserve = reserve1; } if (bonded == 0) { return (0, totalReserve); } reserve = totalReserve.mul(bonded).div(IUniswapV2Pair(pool).totalSupply()); } function _getSellAndReturnAmount( uint256 price, uint256 targetPrice, uint256 reserve ) internal pure returns (uint256 sellAmount, uint256 returnAmount) { // price in resolution 1e18 sellAmount = 0; returnAmount = 0; uint256 rootPoT = Babylonian.sqrt(price.mul(1e36).div(targetPrice)); if (rootPoT > 1e18) { // res error sellAmount = (rootPoT - 1e18).mul(reserve).div(1e18); } uint256 rootPT = Babylonian.sqrt(price.mul(targetPrice)); if (price > rootPT) { // res error returnAmount = (price - rootPT).mul(reserve).div(1e18); } if (sellAmount > returnAmount) { // res error sellAmount = returnAmount; } } function _getBuyAmount(uint256 price, uint256 targetPrice, uint256 reserve) internal pure returns (uint256 shouldBuy) { shouldBuy = 0; uint256 root = Babylonian.sqrt(price.mul(1e36).div(targetPrice)); if (root < 1e18) { // res error shouldBuy = (1e18 - root).mul(reserve).div(1e18); } } function getCollateralRatio() internal view returns (uint256) { return _state.collateralRatio; } } // File: contracts/external/UniswapV2Library.sol pragma solidity >=0.5.0; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/dao/Setters.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Setters is State, Getters { using SafeMath for uint256; using SafeERC20 for IERC20; event Claim(address indexed pool, address indexed account, uint256 value); /** * Global */ function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.sub(amount); } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount); } function decrementTotalClippable(uint256 amount) internal { _state.balance.clippable = _state.balance.clippable.sub(amount); } function incrementTotalClippable(uint256 amount) internal { _state.balance.clippable = _state.balance.clippable.add(amount); } /** * Account */ function incrementBalanceOfBonded(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].bonded = _state.pools[pool].accounts[account].bonded.add(amount); _state.pools[pool].bonded = _state.pools[pool].bonded.add(amount); } function decrementBalanceOfBonded(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].bonded = _state.pools[pool].accounts[account].bonded.sub(amount); _state.pools[pool].bonded = _state.pools[pool].bonded.sub(amount); } function incrementBalanceOfStaged(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].staged = _state.pools[pool].accounts[account].staged.add(amount); _state.pools[pool].staged = _state.pools[pool].staged.add(amount); } function decrementBalanceOfStaged(address pool, address account, uint256 amount) internal { _state.pools[pool].accounts[account].staged = _state.pools[pool].accounts[account].staged.sub(amount); _state.pools[pool].staged = _state.pools[pool].staged.sub(amount); } function incrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.add(amount); _state.balance.coupons = _state.balance.coupons.add(amount); } function decrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.sub(amount); _state.balance.coupons = _state.balance.coupons.sub(amount); } function clipRedeemedCoupon(address account, uint256 epoch) internal returns (uint256 vsdRedeemable) { uint256 couponRedeemed = _state.accounts[account].coupons[epoch]; _state.accounts[account].coupons[epoch] = 0; // require(_state.epochs[epoch].coupons.outstanding == 0); vsdRedeemable = _state.epochs[epoch].coupons.vsdRedeemable.mul(couponRedeemed).div(_state.epochs[epoch].coupons.couponRedeemed); } function unfreeze(address pool, address account) internal { _state.pools[pool].accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub(amount); } /** * Epoch */ function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); } function snapshotDollarTotalSupply() internal { _state.epochs[epoch()].totalDollarSupply = dollar().totalSupply(); } function redeemOutstandingCoupons(uint256 epoch) internal returns (uint256 couponRedeemed, uint256 vsdRedeemable) { uint256 outstandingCouponsForEpoch = outstandingCoupons(epoch); if(outstandingCouponsForEpoch == 0) { return (0, 0); } _state.balance.coupons = _state.balance.coupons.sub(outstandingCouponsForEpoch); uint256 totalRedeemable = totalRedeemable(); vsdRedeemable = outstandingCouponsForEpoch; couponRedeemed = outstandingCouponsForEpoch; if (totalRedeemable < vsdRedeemable) { // Partial redemption vsdRedeemable = totalRedeemable; } _state.epochs[epoch].coupons.couponRedeemed = outstandingCouponsForEpoch; _state.epochs[epoch].coupons.vsdRedeemable = vsdRedeemable; _state.epochs[epoch].coupons.outstanding = 0; } /** * Governance */ function createCandidate(uint256 candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVoteInfo(address account, uint256 candidate, Candidate.VoteInfo memory voteInfo) internal { _state.candidates[candidate].votes[account] = voteInfo; } function incrementApproveFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount); } function incrementRejectFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor(uint256 candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount); } function placeLock(address account, uint256 candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(uint256 candidate) internal { _state.candidates[candidate].initialized = true; } /** * Pool */ function _addPool(address pool) internal { uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { require(pool != _state.poolList[i], "Must not be added"); } _state.pools[pool].flags = 0x1; // enable flag _state.poolList.push(pool); } function preClaimDollar(address pool) internal { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; require((poolInfo.flags & 0x1) == 0x1, "pool is disabled"); if (user.bonded > 0) { uint256 pending = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18).sub(user.rewardDebt); if (pending > 0) { // Safe transfer to avoid resolution error. uint256 balance = dollar().balanceOf(address(this)); if (pending > balance) { pending = balance; } dollar().transfer(msg.sender, pending); emit Claim(msg.sender, pool, pending); } } } function postClaimDollar(address pool) internal { Storage.PoolInfo storage poolInfo = _state.pools[pool]; Account.PoolState storage user = poolInfo.accounts[msg.sender]; user.rewardDebt = user.bonded.mul(poolInfo.accDollarPerLP).div(1e18); } function _addLiquidity(address pool, address token, address anotherToken, uint256 amount) internal returns (uint256) { address token0 = IUniswapV2Pair(pool).token0(); address token1 = IUniswapV2Pair(pool).token1(); require(token == token0 || token == token1, "token must in pool"); require(anotherToken == token0 || anotherToken == token1, "atoken must in pool"); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pool).getReserves(); (uint256 reserveToken, uint256 reserveAnother) = token == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 anotherAmount = UniswapV2Library.quote(amount, reserveToken, reserveAnother); // throw if reserve is zero IERC20(token).safeTransferFrom(msg.sender, pool, amount); IERC20(anotherToken).safeTransferFrom(msg.sender, pool, anotherAmount); return IUniswapV2Pair(pool).mint(address(this)); } function _sellAndDepositCollateral(uint256 totalSellAmount, uint256 allReserve) internal { if (totalSellAmount == 0 || allReserve == 0) { return; } dollar().mint(address(this), totalSellAmount); uint256 len = _state.poolList.length; uint256 actualSold = 0; // Sell to pools according to their reserves for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; address token0 = IUniswapV2Pair(pool).token0(); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pool).getReserves(); uint256 reserveA = token0 == address(dollar()) ? reserve0 : reserve1; uint256 reserveB = token0 == address(dollar()) ? reserve1 : reserve0; uint256 sellAmount = totalSellAmount .mul(reserveA) .div(allReserve); actualSold = actualSold.add(sellAmount); if (reserveA == 0 || sellAmount == 0) { // The pool is not ready yet or insufficient lp in pool. continue; } uint256 assetAmount = UniswapV2Library.getAmountOut( sellAmount, reserveA, reserveB ); dollar().transfer(pool, sellAmount); // Non-Reentrancy? IUniswapV2Pair(pool).swap( token0 == address(dollar()) ? 0 : assetAmount, token0 == address(dollar()) ? assetAmount : 0, address(this), new bytes(0) ); } // Make sure we don't sell extra assert(actualSold <= totalSellAmount); } /** * Collateral */ function _addCollateral(address asset) internal { uint256 len = _state.collateralAssetList.length; for (uint256 i = 0; i < len; i++) { require(asset != _state.collateralAssetList[i], "Must not be added"); } _state.collateralAssetList.push(asset); } } // File: contracts/external/Require.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } // File: contracts/dao/Comptroller.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Comptroller is Setters { using SafeMath for uint256; bytes32 private constant FILE = "Comptroller"; function mintToAccount(address account, uint256 amount) internal { dollar().mint(account, amount); increaseDebt(amount); balanceCheck(); } function burnFromAccount(address account, uint256 amount) internal { burnFromAccountForDebt(account, amount, amount); } function burnFromAccountForDebt(address account, uint256 amount, uint256 debtAmount) internal { dollar().transferFrom(account, address(this), amount); dollar().burn(amount); decrementTotalDebt(debtAmount); balanceCheck(); } function clipToAccount(address account, uint256 amount) internal { dollar().transfer(account, amount); decrementTotalClippable(amount); balanceCheck(); } function redeemToClippable(uint256 amount) internal { decrementTotalRedeemable(amount); incrementTotalClippable(amount); balanceCheck(); } function setDebt(uint256 amount) internal returns (uint256) { _state.balance.debt = amount; uint256 lessDebt = resetDebt(Constants.getDebtRatioCap()); balanceCheck(); return lessDebt > amount ? 0 : amount.sub(lessDebt); } function increaseDebt(uint256 amount) internal returns (uint256) { incrementTotalDebt(amount); uint256 lessDebt = resetDebt(Constants.getDebtRatioCap()); balanceCheck(); return lessDebt > amount ? 0 : amount.sub(lessDebt); } function decreaseDebt(uint256 amount) internal { decrementTotalDebt(amount); balanceCheck(); } function _updateReserve() internal returns (uint256 allReserve) { uint256 totalAllocPoint = 0; uint256 len = _state.poolList.length; allReserve = 0; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; uint256 poolReserve; (poolInfo.allocPoint, poolReserve) = _getDollarReserve(pool, _state.pools[pool].bonded); totalAllocPoint = totalAllocPoint.add(poolInfo.allocPoint); allReserve = allReserve.add(poolReserve); } _state.totalAllocPoint = totalAllocPoint; } function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256) { // 0. Pay out to Fund uint256 rewards = newSupply.mul(getSupplyIncreaseFundRatio()).div(10000); uint256 devReward = rewards.mul(Constants.getFundDevPct()).div(100); uint256 treasuryReward = rewards.sub(devReward); if (devReward != 0) { dollar().mint(Constants.getDevAddress(), devReward); } if (treasuryReward != 0) { dollar().mint(Constants.getTreasuryAddress(), treasuryReward); } newSupply = newSupply > rewards ? newSupply.sub(rewards) : 0; // 1. True up redeemable pool uint256 newRedeemable = 0; uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); } // 2. Payout to LPs if (!mintToLPs(newSupply)) { newSupply = 0; } balanceCheck(); return (newRedeemable, newSupply.add(rewards), newSupply); } function resetDebt(Decimal.D256 memory targetDebtRatio) internal returns (uint256) { uint256 targetDebt = targetDebtRatio.mul(dollar().totalSupply()).asUint256(); uint256 currentDebt = totalDebt(); if (currentDebt > targetDebt) { uint256 lessDebt = currentDebt.sub(targetDebt); decreaseDebt(lessDebt); return lessDebt; } return 0; } function balanceCheck() private { // Require.that( // dollar().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()).add(totalClippable()), // FILE, // "Inconsistent balances" // ); } function mintToLPs(uint256 amount) private returns (bool) { if (amount == 0) { return false; } if (_state.totalAllocPoint == 0) { return false; } dollar().mint(address(this), amount); uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; if (poolInfo.bonded == 0) { continue; } uint256 poolAmount = amount.mul(poolInfo.allocPoint).div(_state.totalAllocPoint); poolInfo.accDollarPerLP = poolInfo.accDollarPerLP.add(poolAmount.mul(1e18).div(poolInfo.bonded)); } return true; } function mintToRedeemable(uint256 amount) private { dollar().mint(address(this), amount); incrementTotalRedeemable(amount); balanceCheck(); } /* for testing purpose */ function getSupplyIncreaseFundRatio() internal view returns (uint256) { return Constants.getSupplyIncreaseFundRatio(); } } // File: contracts/dao/Market.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Market is Comptroller, Curve { using SafeMath for uint256; bytes32 private constant FILE = "Market"; event CouponRedemption(uint256 indexed epoch, uint256 couponRedeemed, uint256 vsdRedeemable); event CouponPurchase(address indexed account, uint256 indexed epochExpire, uint256 dollarAmount, uint256 couponAmount); event CouponClip(address indexed account, uint256 indexed epoch, uint256 couponAmount); event CouponTransfer(address indexed from, address indexed to, uint256 indexed epoch, uint256 value); event CouponApproval(address indexed owner, address indexed spender, uint256 value); event CouponExtended(address indexed owner, uint256 indexed epoch, uint256 couponAmount, uint256 newCouponAmount, uint256 newExpiration); function step() internal { // Automatically redeem prior coupons redeemCouponsForEpoch(epoch()); } function redeemCouponsForEpoch(uint256 epoch) private { (uint256 couponRedeemed, uint256 vsdRedeemable) = redeemOutstandingCoupons(epoch); redeemToClippable(vsdRedeemable); emit CouponRedemption(epoch, couponRedeemed, vsdRedeemable); } function couponPremium(uint256 amount) public view returns (uint256) { return calculateCouponPremium(dollar().totalSupply(), totalDebt(), amount); } function purchaseCoupons(uint256 dollarAmount) external returns (uint256) { Require.that( dollarAmount > 0, FILE, "Must purchase non-zero amount" ); Require.that( totalDebt() >= dollarAmount, FILE, "Not enough debt" ); uint256 epoch = epoch(); uint256 couponAmount = dollarAmount.add(couponPremium(dollarAmount)); burnFromAccount(msg.sender, dollarAmount); incrementBalanceOfCoupons(msg.sender, epoch.add(Constants.getCouponExpiration()), couponAmount); emit CouponPurchase(msg.sender, epoch.add(Constants.getCouponExpiration()), dollarAmount, couponAmount); return couponAmount; } /* * @dev Extend the expiration of a coupon by VSDs. */ function extendCoupon(uint256 couponExpireEpoch, uint256 couponAmount, uint256 dollarAmount) external { Require.that( dollarAmount > 0, FILE, "Must purchase non-zero amount" ); uint256 epoch = epoch(); decrementBalanceOfCoupons(msg.sender, couponExpireEpoch, couponAmount); uint256 liveness = couponAmount.mul(couponExpireEpoch.sub(epoch)); uint256 debtAmount = totalDebt(); if (debtAmount > dollarAmount) { debtAmount = dollarAmount; } burnFromAccountForDebt(msg.sender, dollarAmount, debtAmount); liveness = liveness.add(dollarAmount.mul(Constants.getCouponExpiration())); uint256 newExpiration = liveness.div(couponAmount).add(epoch); Require.that( newExpiration > epoch, FILE, "Must new exp. > current epoch" ); incrementBalanceOfCoupons(msg.sender, newExpiration, couponAmount); emit CouponExtended(msg.sender, couponExpireEpoch, couponAmount, couponAmount, newExpiration); } function clipCoupons(uint256 couponExpireEpoch) external { Require.that( outstandingCoupons(couponExpireEpoch) == 0, FILE, "Coupon is not redeemed" ); uint256 vsdAmount = clipRedeemedCoupon(msg.sender, couponExpireEpoch); clipToAccount(msg.sender, vsdAmount); emit CouponClip(msg.sender, couponExpireEpoch, vsdAmount); } function approveCoupons(address spender, uint256 amount) external { Require.that( spender != address(0), FILE, "Coupon approve to 0x0" ); updateAllowanceCoupons(msg.sender, spender, amount); emit CouponApproval(msg.sender, spender, amount); } function transferCoupons(address sender, address recipient, uint256 epoch, uint256 amount) external { Require.that( sender != address(0), FILE, "Coupon transfer from 0x0" ); Require.that( recipient != address(0), FILE, "Coupon transfer to 0x0" ); decrementBalanceOfCoupons(sender, epoch, amount); incrementBalanceOfCoupons(recipient, epoch, amount); if (msg.sender != sender && allowanceCoupons(sender, msg.sender) != uint256(-1)) { decrementAllowanceCoupons(sender, msg.sender, amount); } emit CouponTransfer(sender, recipient, epoch, amount); } } // File: contracts/dao/Regulator.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Regulator is Comptroller { using SafeMath for uint256; using Decimal for Decimal.D256; event Incentivization(address indexed account, uint256 amount); event SupplyIncrease(uint256 indexed epoch, uint256 price, uint256 newSell, uint256 newRedeemable, uint256 lessDebt, uint256 newSupply, uint256 newReward); event SupplyDecrease(uint256 indexed epoch, uint256 price, uint256 newDebt); event SupplyNeutral(uint256 indexed epoch); function step() internal { Decimal.D256 memory price = oracleCapture(); uint256 allReserve = _updateReserve(); if (price.greaterThan(Decimal.D256({value: getSupplyIncreasePriceThreshold()}))) { incentivize(msg.sender, Constants.getExpansionAdvanceIncentive()); growSupply(price, allReserve); return; } incentivize(msg.sender, Constants.getAdvanceIncentive()); if (price.lessThan(Decimal.D256({value: getSupplyDecreasePriceThreshold()}))) { shrinkSupply(price, allReserve); return; } emit SupplyNeutral(epoch()); } function incentivize(address account, uint256 amount) private { mintToAccount(account, amount); emit Incentivization(account, amount); } function shrinkSupply(Decimal.D256 memory price, uint256 allReserve) private { uint256 newDebt = _getBuyAmount(price.value, getSupplyDecreasePriceTarget(), allReserve); uint256 cappedNewDebt = setDebt(newDebt); emit SupplyDecrease(epoch(), price.value, cappedNewDebt); return; } function growSupply(Decimal.D256 memory price, uint256 allReserve) private { uint256 lessDebt = resetDebt(Decimal.zero()); (uint256 sellAmount, uint256 returnAmount) = _getSellAndReturnAmount( price.value, getSupplyIncreasePriceTarget(), allReserve ); _sellAndDepositCollateral(sellAmount, allReserve); uint256 mintAmount = returnAmount.mul(10000).div(getCollateralRatio()); (uint256 newRedeemable, uint256 newSupply, uint256 newReward) = increaseSupply(mintAmount.sub(sellAmount)); emit SupplyIncrease(epoch(), price.value, sellAmount, newRedeemable, lessDebt, newSupply, newReward); } function oracleCapture() private returns (Decimal.D256 memory) { (Decimal.D256 memory price, bool valid) = oracle().capture(); if (!valid) { return Decimal.one(); } return price; } /* for testing purpose */ function getSupplyIncreasePriceThreshold() internal view returns (uint256) { return Constants.getSupplyIncreasePriceThreshold(); } function getSupplyIncreasePriceTarget() internal view returns (uint256) { return Constants.getSupplyIncreasePriceTarget(); } function getSupplyDecreasePriceThreshold() internal view returns (uint256) { return Constants.getSupplyDecreasePriceThreshold(); } function getSupplyDecreasePriceTarget() internal view returns (uint256) { return Constants.getSupplyDecreasePriceTarget(); } } // File: contracts/dao/Permission.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Permission is Setters { bytes32 private constant FILE = "Permission"; // Can modify account state modifier onlyFrozenOrFluid(address pool, address account) { Require.that( statusOf(pool, account) != Account.Status.Locked, FILE, "Not frozen or fluid" ); _; } // Can participate in balance-dependant activities modifier onlyFrozen(address pool, address account) { Require.that( statusOf(pool, account) == Account.Status.Frozen, FILE, "Not frozen" ); _; } modifier initializer() { Require.that( !isInitialized(uint256(implementation())), FILE, "Already initialized" ); initialized(uint256(implementation())); _; } } // File: contracts/dao/Bonding.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Bonding is Setters, Permission { using SafeMath for uint256; bytes32 private constant FILE = "Bonding"; event Deposit(address indexed pool, address indexed account, uint256 value); event Withdraw(address indexed pool, address indexed account, uint256 value); event Bond(address indexed pool, address indexed account, uint256 start, uint256 value); event Unbond(address indexed pool, address indexed account, uint256 start, uint256 value); function step() internal { Require.that( epochTime() > epoch(), FILE, "Still current epoch" ); snapshotDollarTotalSupply(); incrementEpoch(); } function addPool(address pool) external { Require.that( msg.sender == address(this), FILE, "Must from governance" ); _addPool(pool); } function claim(address pool) external { preClaimDollar(pool); postClaimDollar(pool); } function deposit(address pool, uint256 value) external { IERC20(pool).transferFrom(msg.sender, address(this), value); incrementBalanceOfStaged(pool, msg.sender, value); emit Deposit(pool, msg.sender, value); } function withdraw(address pool, uint256 value) external onlyFrozen(pool, msg.sender) { IERC20(pool).transfer(msg.sender, value); decrementBalanceOfStaged(pool, msg.sender, value); emit Withdraw(pool, msg.sender, value); } function bond(address pool, uint256 value) external { preClaimDollar(pool); unfreeze(pool, msg.sender); incrementBalanceOfBonded(pool, msg.sender, value); decrementBalanceOfStaged(pool, msg.sender, value); emit Bond(pool, msg.sender, epoch().add(1), value); postClaimDollar(pool); } function unbond(address pool, uint256 value) external onlyFrozenOrFluid(pool, msg.sender) { preClaimDollar(pool); unfreeze(pool, msg.sender); incrementBalanceOfStaged(pool, msg.sender, value); decrementBalanceOfBonded(pool, msg.sender, value); emit Unbond(pool, msg.sender, epoch().add(1), value); postClaimDollar(pool); } function provide(address pool, address token, address another, uint256 amount) external { preClaimDollar(pool); unfreeze(pool, msg.sender); uint256 bondedLP = _addLiquidity(pool, token, another, amount); incrementBalanceOfBonded(pool, msg.sender, bondedLP); emit Bond(pool, msg.sender, epoch().add(1), bondedLP); postClaimDollar(pool); } } // File: @openzeppelin/upgrades/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/dao/Upgradeable.sol /* Copyright 2018-2019 zOS Global Limited Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; /** * Based off of, and designed to interface with, openzeppelin/upgrades package */ contract Upgradeable is State { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); function initialize() public; /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) internal { setImplementation(newImplementation); (bool success, bytes memory reason) = newImplementation.delegatecall(abi.encodeWithSignature("initialize()")); require(success, string(reason)); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function setImplementation(address newImplementation) private { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: contracts/dao/Govern.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Govern is Setters, Permission, Upgradeable { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant FILE = "Govern"; event Proposal(uint256 indexed candidate, address indexed account, uint256 indexed start, uint256 period); event Vote(address indexed account, uint256 indexed candidate, Candidate.Vote vote, uint256 bondedVotes); event Commit(address indexed account, uint256 indexed candidate, bool upgrade); /* * We allow voting as long as the token is bonded. */ function vote(uint256 candidate, Candidate.Vote vote) external { Require.that( msg.sender == tx.origin, FILE, "Must be a user tx" ); if (!isNominated(candidate)) { Require.that( canPropose(msg.sender), FILE, "Not enough stake to propose" ); createCandidate(candidate, Constants.getGovernancePeriod()); emit Proposal(candidate, msg.sender, epoch(), Constants.getGovernancePeriod()); } Require.that( epoch() < startFor(candidate).add(periodFor(candidate)), FILE, "Ended" ); uint256 bondedVotes = balanceOfBondedDollar(msg.sender); Candidate.VoteInfo memory recordedVoteInfo = recordedVoteInfo(msg.sender, candidate); Candidate.VoteInfo memory newVoteInfo = Candidate.VoteInfo({vote: vote, bondedVotes: bondedVotes}); if (newVoteInfo.vote == recordedVoteInfo.vote && newVoteInfo.bondedVotes == recordedVoteInfo.bondedVotes) { return; } if (recordedVoteInfo.vote == Candidate.Vote.REJECT) { decrementRejectFor(candidate, recordedVoteInfo.bondedVotes); } if (recordedVoteInfo.vote == Candidate.Vote.APPROVE) { decrementApproveFor(candidate, recordedVoteInfo.bondedVotes); } if (vote == Candidate.Vote.REJECT) { incrementRejectFor(candidate, newVoteInfo.bondedVotes); } if (vote == Candidate.Vote.APPROVE) { incrementApproveFor(candidate, newVoteInfo.bondedVotes); } recordVoteInfo(msg.sender, candidate, newVoteInfo); placeLock(msg.sender, candidate); emit Vote(msg.sender, candidate, vote, bondedVotes); } function commit(uint256 candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); uint256 endsAfter = startFor(candidate).add(periodFor(candidate)).sub(1); Require.that( epoch() > endsAfter, FILE, "Not ended" ); Require.that( epoch() <= endsAfter.add(1).add(Constants.getGovernanceExpiration()), FILE, "Expired" ); Require.that( Decimal.ratio(votesFor(candidate), dollar().totalSupply()).greaterThan(Constants.getGovernanceQuorum()), FILE, "Must have quorom" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); Require.that( msg.sender == getGovernor(), FILE, "Must from governor" ); upgradeTo(address(candidate)); emit Commit(msg.sender, candidate, true); } function emergencyCommit(uint256 candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); Require.that( Decimal.ratio(approveFor(candidate), dollar().totalSupply()).greaterThan(Constants.getGovernanceSuperMajority()), FILE, "Must have super majority" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); Require.that( msg.sender == getGovernor(), FILE, "Must from governor" ); upgradeTo(address(candidate)); emit Commit(msg.sender, candidate, true); } function canPropose(address account) private view returns (bool) { Decimal.D256 memory stake = Decimal.ratio( balanceOfBondedDollar(account), dollar().totalSupply() ); return stake.greaterThan(Constants.getGovernanceProposalThreshold()); } function getGovernor() internal view returns (address) { return Constants.getGovernor(); } } // File: contracts/dao/ReentrancyGuard.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/dao/Collateral.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Collateral is Comptroller, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; bytes32 private constant FILE = "Collateral"; function redeem(uint256 value) external nonReentrant { uint256 actual = value; uint256 debt = totalDebt(); if (debt > value) { // if there is debt, redeem at no cost debt = value; } else { // redeem with cost actual = value.sub((10000 - Constants.getRedemptionRate()).mul(value.sub(debt)).div(10000)); uint256 fundReward = value.sub(actual); uint256 devReward = fundReward.mul(Constants.getFundDevPct()).div(100); uint256 treasuryReward = fundReward.sub(devReward); dollar().transferFrom(msg.sender, Constants.getDevAddress(), devReward); dollar().transferFrom(msg.sender, Constants.getTreasuryAddress(), treasuryReward); } uint256 len = _state.collateralAssetList.length; uint256 dollarTotalSupply = dollar().totalSupply(); for (uint256 i = 0; i < len; i++) { address addr = _state.collateralAssetList[i]; IERC20(addr).safeTransfer( msg.sender, actual.mul(IERC20(addr).balanceOf(address(this))).div(dollarTotalSupply) ); } burnFromAccountForDebt(msg.sender, actual, debt); } function addCollateral(address asset) external { Require.that( msg.sender == address(this), FILE, "Must from governance" ); _addCollateral(asset); } function _getMinterAddress() internal view returns (address) { return Constants.getMinterAddress(); } } // File: contracts/dao/Implementation.sol /* Copyright 2020 Empty Set Squad <[email protected]> Copyright 2021 vsdcrew <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.16; contract Implementation is State, Bonding, Market, Regulator, Govern, Collateral { using SafeMath for uint256; event Advance(uint256 indexed epoch, uint256 block, uint256 timestamp); function initialize() initializer public { /* uint256 len = _state.poolList.length; for (uint256 i = 0; i < len; i++) { address pool = _state.poolList[i]; Storage.PoolInfo storage poolInfo = _state.pools[pool]; poolInfo.flags = 0x1; } */ } function advance() nonReentrant external { require (msg.sender == tx.origin, "Must from user"); Bonding.step(); Regulator.step(); Market.step(); emit Advance(epoch(), block.number, block.timestamp); } }
0. Pay out to Fund 2. Payout to LPs
function increaseSupply(uint256 newSupply) internal returns (uint256, uint256, uint256) { uint256 rewards = newSupply.mul(getSupplyIncreaseFundRatio()).div(10000); uint256 devReward = rewards.mul(Constants.getFundDevPct()).div(100); uint256 treasuryReward = rewards.sub(devReward); if (devReward != 0) { dollar().mint(Constants.getDevAddress(), devReward); } if (treasuryReward != 0) { dollar().mint(Constants.getTreasuryAddress(), treasuryReward); } newSupply = newSupply > rewards ? newSupply.sub(rewards) : 0; uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); } if (!mintToLPs(newSupply)) { newSupply = 0; } balanceCheck(); return (newRedeemable, newSupply.add(rewards), newSupply); }
1,966,518
//Address: 0x76531ec44dd24903fd5f2742f71ca96e95ea7d30 //Contract name: Items //Balance: 0 Ether //Verification Date: 3/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.21; contract Items{ address owner; address helper = 0x690F34053ddC11bdFF95D44bdfEb6B0b83CBAb58; // Marketplace written by Etherguy and Poorguy // Change the below numbers to edit the development fee. // This can also be done by calling SetDevFee and SetHFee // Numbers are divided by 10000 to calcualte the cut uint16 public DevFee = 500; // 500 / 10000 -> 5% uint16 public HelperPortion = 5000; // 5000 / 10000 -> 50% (This is the cut taken from the total dev fee) // Increase in price // 0 means that the price stays the same // Again divide by 10000 // 10000 means: 10000/10000 = 1, which means the new price = OldPrice * (1 + (10000/1000)) = OldPrice * (1+1) = 2*OldPrice // Hence the price doubles. // This setting can be changed via SetPriceIncrease // The maximum setting is the uint16 max value 65535 which means an insane increase of more than 6.5x uint16 public PriceIncrease = 2000; struct Item{ address Owner; uint256 Price; } mapping(uint256 => Item) Market; uint256 public NextItemID = 0; event ItemBought(address owner, uint256 id, uint256 newprice); function Items() public { owner = msg.sender; // Add initial items here to created directly by contract release. // AddMultipleItems(0.00666 ether, 3); // Create 3 items for 0.00666 ether basic price at start of contract. // INITIALIZE 17 items so we can transfer ownership ... AddMultipleItems(0.006666 ether, 36); // SETUP their data Market[0].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[0].Price = 53280000000000000; Market[1].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[1].Price = 26640000000000000; Market[2].Owner = 0xb080b202b921d0d1fd804d0071615eb09e326aac; Market[2].Price = 854280000000000000; Market[3].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[3].Price = 26640000000000000; Market[4].Owner = 0xb080b202b921d0d1fd804d0071615eb09e326aac; Market[4].Price = 213120000000000000; Market[5].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[5].Price = 13320000000000000; Market[6].Owner = 0xd33614943bcaadb857a58ff7c36157f21643df36; Market[6].Price = 26640000000000000; Market[7].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[7].Price = 53280000000000000; Market[8].Owner = 0xd33614943bcaadb857a58ff7c36157f21643df36; Market[8].Price = 26640000000000000; Market[9].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[9].Price = 53280000000000000; Market[10].Owner = 0x0960069855bd812717e5a8f63c302b4e43bad89f; Market[10].Price = 13320000000000000; Market[11].Owner = 0xd3dead0690e4df17e4de54be642ca967ccf082b8; Market[11].Price = 13320000000000000; Market[12].Owner = 0xc34434842b9dc9cab4e4727298a166be765b4f32; Market[12].Price = 13320000000000000; Market[13].Owner = 0xc34434842b9dc9cab4e4727298a166be765b4f32; Market[13].Price = 13320000000000000; Market[14].Owner = 0x874c6f81c14f01c0cb9006a98213803cd7af745f; Market[14].Price = 53280000000000000; Market[15].Owner = 0xd33614943bcaadb857a58ff7c36157f21643df36; Market[15].Price = 26640000000000000; Market[16].Owner = 0x3130259deedb3052e24fad9d5e1f490cb8cccaa0; Market[16].Price = 13320000000000000; // Uncomment to add MORE ITEMS // AddMultipleItems(0.006666 ether, 17); } // web function, return item info function ItemInfo(uint256 id) public view returns (uint256 ItemPrice, address CurrentOwner){ return (Market[id].Price, Market[id].Owner); } // Add a single item. function AddItem(uint256 price) public { require(price != 0); // Price 0 means item is not available. require(msg.sender == owner); Item memory ItemToAdd = Item(0x0, price); // Set owner to 0x0 -> Recognized as owner Market[NextItemID] = ItemToAdd; NextItemID = add(NextItemID, 1); // This absolutely prevents overwriting items } // Add multiple items // All for same price // This saves sending 10 tickets to create 10 items. function AddMultipleItems(uint256 price, uint8 howmuch) public { require(msg.sender == owner); require(price != 0); require(howmuch != 255); // this is to prevent an infinite for loop uint8 i=0; for (i; i<howmuch; i++){ AddItem(price); } } function BuyItem(uint256 id) payable public{ Item storage MyItem = Market[id]; require(MyItem.Price != 0); // It is not possible to edit existing items. require(msg.value >= MyItem.Price); // Pay enough thanks . uint256 ValueLeft = DoDev(MyItem.Price); uint256 Excess = sub(msg.value, MyItem.Price); if (Excess > 0){ msg.sender.transfer(Excess); // Pay back too much sent } // Proceed buy address target = MyItem.Owner; // Initial items are owned by owner. if (target == 0x0){ target = owner; } target.transfer(ValueLeft); // set owner and price. MyItem.Price = mul(MyItem.Price, (uint256(PriceIncrease) + uint256(10000)))/10000; // division 10000 to scale stuff right. No need SafeMath this only errors when DIV by 0. MyItem.Owner = msg.sender; emit ItemBought(msg.sender, id, MyItem.Price); } // Management stuff, not interesting after here . function DoDev(uint256 val) internal returns (uint256){ uint256 tval = (mul(val, DevFee)) / 10000; uint256 hval = (mul(tval, HelperPortion)) / 10000; uint256 dval = sub(tval, hval); owner.transfer(dval); helper.transfer(hval); return (sub(val,tval)); } // allows to change dev fee. max is 6.5% function SetDevFee(uint16 tfee) public { require(msg.sender == owner); require(tfee <= 650); DevFee = tfee; } // allows to change helper fee. minimum is 10%, max 100%. function SetHFee(uint16 hfee) public { require(msg.sender == owner); require(hfee <= 10000); HelperPortion = hfee; } // allows to change helper fee. minimum is 10%, max 100%. function SetPriceIncrease(uint16 increase) public { require(msg.sender == owner); PriceIncrease = increase; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Add multiple items All for same price This saves sending 10 tickets to create 10 items.
function AddMultipleItems(uint256 price, uint8 howmuch) public { require(msg.sender == owner); require(price != 0); uint8 i=0; for (i; i<howmuch; i++){ AddItem(price); } }
956,400
./full_match/3/0x6EA839B1DD0C21DCFaF7e493c97B5E4027039df3/sources/contracts/ERC20Detailed.sol
This function is called to find whether the message sender is a token validate or notIf token cut off date at launchIf tokens are sent from Smart Contract, then it needs multi party approvalIf maximum allowed tokens per account
function isTokenValidate(address to, uint256 value) private view returns (bool) { if(block.timestamp<=_tokenAllowedCutOffDate){ if(PriorApprovalERC20(_priorApprovalContractAddress).verifyPriorApprovalERC20(to) == false) { uint256 totalTokenValue = _balances[to]+value; if(_tokenAllowedPerAccount<totalTokenValue){ return false; } } } return true; }
8,137,143
./full_match/1/0x65fff8F5f6a9922b6dC13fE06345a0Fe46Dd413D/sources/contracts/VFAccessControl.sol
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == type(IVFAccessControl).interfaceId || super.supportsInterface(interfaceId); }
4,972,427
pragma solidity ^0.4.24; /*********************************************************** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless ***********************************************************/ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } /*********************************************************** * NameFilter library ***********************************************************/ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /*********************************************************** * NTech3DDatasets library ***********************************************************/ library NTech3DDatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 NTAmount; // amount distributed to nt uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256 prevres; // 上一轮或者奖池互换流入本轮的奖金 } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 nt; // % of buy in thats paid to nt holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 nt; // % of pot thats paid to NT foundation } } /*********************************************************** interface : OtherNTech3D 主要用作奖池互换 ***********************************************************/ interface OtherNTech3D { function potSwap() external payable; } /*********************************************************** * NTech3DKeysCalcLong library ***********************************************************/ library NTech3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } /*********************************************************** * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 ***********************************************************/ contract ERC20 { function totalSupply() public view returns (uint supply); function balanceOf( address who ) public view returns (uint value); function allowance( address owner, address spender ) public view returns (uint _allowance); function transfer( address to, uint value) public returns (bool ok); function transferFrom( address from, address to, uint value) public returns (bool ok); function approve( address spender, uint value ) public returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } /*********************************************************** interface : PlayerBookInterface ***********************************************************/ interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } /*********************************************************** * NTech3DLong contract ***********************************************************/ contract NTech3DLong { /****************************************************************************************** 导入的库 */ using SafeMath for *; using NameFilter for string; using NTech3DKeysCalcLong for uint256; /****************************************************************************************** 事件 */ // 当玩家注册名字时调用 event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // 购买完成后或者再次载入时调用 event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 NTAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // 撤退时调用 event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // 当撤退并且分发时调用 event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 NTAmount, uint256 genAmount ); // 当一轮时间过后,有玩家试图购买时调用 event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 NTAmount, uint256 genAmount ); //当一轮时间过后,有玩家重载时调用 event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 NTAmount, uint256 genAmount ); // 附属账号有支付时调用 event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // 收到奖池存款调用 event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); /****************************************************************************************** 合约权限管理 设计:会设计用户权限管理, 9 => 管理员角色 0 => 没有任何权限 */ // 用户地址到角色的表 mapping(address => uint256) private users ; // 初始化 function initUsers() private { // 初始化下列地址帐户为管理员 users[0x89b2E7Ee504afd522E07F80Ae7b9d4D228AF3fe2] = 9 ; users[msg.sender] = 9 ; } // 是否是管理员 modifier isAdmin() { uint256 role = users[msg.sender]; require((role==9), "Must be admin."); _; } /****************************************************************************************** 检查是帐户地址还是合约地址 */ modifier isHuman { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "Humans only"); _; } /****************************************************************************************** 关联合约定义 */ // 玩家信息数据库合约 PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x410526CD583AF0bE0530166d53Efcd7da969F7B7); /****************************************************************************************** 社区地址 NT基金地址 代币空投的收款地址 */ address public communityAddr_; address public NTFoundationAddr_; address private NTTokenSeller_ ; /****************************************************************************************** 设置代币地址 条件: 1. 地址不能为空 2. 管理员 */ ERC20 private NTToken_ ; function setNTToken(address addr) isAdmin() public { require(address(addr) != address(0x0), "Empty address not allowed."); NTToken_ = ERC20(addr); } /** 将游戏合约中的未用完的代币转走 条件: 1. 数值大于0 2. 管理员 */ function transfer(address toAddr, uint256 amount) isAdmin() public returns (bool) { require(amount > 0, "Must > 0 "); NTToken_.transfer(toAddr, amount); return true ; } /****************************************************************************************** 启动 */ bool public activated_ = false; modifier isActivated() { require(activated_ == true, "its not active yet."); _; } /** TODO 激活游戏 条件: 1、要是管理员 2、要设定代币地址 3、要设定用作奖池呼唤的游戏地址 4、只可以激活一次 */ function activate() isAdmin() public { // 必须设定代币地址 require(address(NTToken_) != address(0x0), "Must setup NTToken."); // 必须设定社区基金地址 require(address(communityAddr_) != address(0x0), "Must setup CommunityAddr_."); // 必须设定购买NT地址 require(address(NTTokenSeller_) != address(0x0), "Must setup NTTokenSeller."); // 必须设定NT基金地址 require(address(NTFoundationAddr_) != address(0x0), "Must setup NTFoundationAddr."); // 只能激活一次 require(activated_ == false, "Only once"); // activated_ = true ; // 初始化开始轮信息 rID_ = 1; round_[1].strt = now ; round_[1].end = now + rndMax_; } /****************************************************************************************** 合约信息 */ string constant public name = "NTech 3D Long Official"; // 合约名称 string constant public symbol = "NT3D"; // 合约符号 /** */ uint256 constant private rndInc_ = 1 minutes; // 每购买一个key延迟的时间 uint256 constant private rndMax_ = 6 hours; // 一轮的最长时间 uint256 private ntOf1Ether_ = 30000; // 一个以太兑换30000代币 /****************************************************************************************** 奖池互换 */ OtherNTech3D private otherNTech3D_ ; // 另外一个游戏接口,主要用作奖池呼唤 /** 设定奖池呼唤的另外一个游戏合约地址 条件 1. 管理员权限 2. 之前没有设定过 3. 设定的地址不能为空 */ function setOtherNTech3D(address _otherNTech3D) isAdmin() public { require(address(_otherNTech3D) != address(0x0), "Empty address not allowed."); require(address(otherNTech3D_) == address(0x0), "OtherNTech3D has been set."); otherNTech3D_ = OtherNTech3D(_otherNTech3D); } /****************************************************************************************** 判断金额 */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "Too little"); require(_eth <= 100000000000000000000000, "Too much"); _; } /****************************************************************************************** 玩家信息 */ // 玩家地址 => 玩家ID mapping (address => uint256) public pIDxAddr_; // 玩家名称 => 玩家ID mapping (bytes32 => uint256) public pIDxName_; // 玩家ID => 玩家信息 mapping (uint256 => NTech3DDatasets.Player) public plyr_; // 玩家ID => 游戏轮编号 => 玩家游戏轮信息 mapping (uint256 => mapping (uint256 => NTech3DDatasets.PlayerRounds)) public plyrRnds_; // 玩家ID => 玩家名称 => mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; /****************************************************************************************** 游戏信息 */ uint256 public rID_; // 当前游戏轮编号 uint256 public airDropPot_; // 空投小奖池 uint256 public airDropTracker_ = 0; // 空投小奖池计数 // 游戏每轮ID => 游戏轮 mapping (uint256 => NTech3DDatasets.Round) public round_; // 游戏每轮ID -> 团队ID => ETH mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; /****************************************************************************************** 团队信息 0 : 水鲸队 1 : 懒熊队 2 : 玩蛇队 3 : 疯牛队 */ // 团队ID => 分配规则 mapping (uint256 => NTech3DDatasets.TeamFee) public fees_; // 团队ID => 分配规则 mapping (uint256 => NTech3DDatasets.PotSplit) public potSplit_; /****************************************************************************************** 构造函数 */ constructor() public { // 水鲸:本轮玩家 30% 空投 6% fees_[0] = NTech3DDatasets.TeamFee(30,6); // 懒熊:本轮玩家 43% 空投 0% fees_[1] = NTech3DDatasets.TeamFee(43,0); // 玩蛇:本轮玩家 56% 空投 10% fees_[2] = NTech3DDatasets.TeamFee(56,10); // 疯牛:本轮玩家 43% 空投 8% fees_[3] = NTech3DDatasets.TeamFee(43,8); // 此轮奖池分配: // 水鲸:本轮玩家 25% potSplit_[0] = NTech3DDatasets.PotSplit(15,10); // 懒熊:本轮玩家 25% potSplit_[1] = NTech3DDatasets.PotSplit(25,0); // 玩蛇:本轮玩家 40% potSplit_[2] = NTech3DDatasets.PotSplit(20,20); // 疯牛:本轮玩家 40% potSplit_[3] = NTech3DDatasets.PotSplit(30,10); // 初始化用户管理 initUsers(); /** */ NTToken_ = ERC20(address(0x09341B5d43a9b2362141675b9276B777470222Be)); communityAddr_ = address(0x3C07f9f7164Bf72FDBefd9438658fAcD94Ed4439); NTTokenSeller_ = address(0x531100a6b3686E6140f170B0920962A5D7A2DD25); NTFoundationAddr_ = address(0x89b2E7Ee504afd522E07F80Ae7b9d4D228AF3fe2); } /****************************************************************************************** 购买 */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID){ _affCode = plyr_[_pID].laff; }else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender){ _affID = plyr_[_pID].laff; }else{ _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff){ plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name){ _affID = plyr_[_pID].laff; }else{ _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff){ plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { NTech3DDatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID){ _affCode = plyr_[_pID].laff; }else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { NTech3DDatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender){ _affID = plyr_[_pID].laff; }else{ _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff){ plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { NTech3DDatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name){ _affID = plyr_[_pID].laff; }else{ _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff){ plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** 撤退 */ function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && (round_[_rID].ended == false) && round_[_rID].plyr != 0){ NTech3DDatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit onWithdrawAndDistribute( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.NTAmount, _eventData_.genAmount ); }else{ _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit onWithdraw( _pID, msg.sender, plyr_[_pID].name, _eth, _now ); } } /****************************************************************************************** 注册 */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable{ bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit onNewName( _pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now ); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable{ bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit onNewName( _pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now ); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable{ bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit onNewName( _pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now ); } /****************************************************************************************** 获取购买价格 */ function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; //if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /****************************************************************************************** 得到剩余时间 */ function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now < round_[_rID].end) //if (_now > round_[_rID].strt + rndGap_) if (_now > round_[_rID].strt) return( (round_[_rID].end).sub(_now) ); else //return( (round_[_rID].strt + rndGap_).sub(_now) ); return( (round_[_rID].end).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0){ // if player is winner if (round_[_rID].plyr == _pID){ // Added by Huwei uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres); return ( // Fix by huwei //(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].win).add( ((_pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { // Fixed by Huwei uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres); return( ((((round_[_rID].mask).add(((((_pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); //return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** 得到当前此轮信息 */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; return ( round_[_rID].ico, _rID, round_[_rID].keys, round_[_rID].end, round_[_rID].strt, round_[_rID].pot, (round_[_rID].team + (round_[_rID].plyr * 10)), plyr_[round_[_rID].plyr].addr, plyr_[round_[_rID].plyr].name, rndTmEth_[_rID][0], rndTmEth_[_rID][1], rndTmEth_[_rID][2], rndTmEth_[_rID][3], airDropTracker_ + (airDropPot_ * 1000) ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256){ uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, plyr_[_pID].name, plyrRnds_[_pID][_rID].keys, plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff, plyrRnds_[_pID][_rID].eth ); } function buyCore(uint256 _pID, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; //if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); }else{ if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit onBuyAndDistribute( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.NTAmount, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, NTech3DDatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; //if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); }else if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit onReLoadAndDistribute( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.NTAmount, _eventData_.genAmount ); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_) private{ if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // 每轮早期的限制 (5 ether 以下) // 智能合约收到的总额达到100 ETH之前,每个以太坊地址最多只能购买总额10个ETH的Key。 if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 10000000000000000000){ uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } if (_eth > 1000000000) { uint256 _keys = (round_[_rID].eth).keysRec(_eth); if (_keys >= 1000000000000000000){ updateTimer(_keys, _rID); if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; _eventData_.compressedData = _eventData_.compressedData + 100; } if (_eth >= 100000000000000000){ // > 0.1 ether, 才有空投 airDropTracker_++; if (airdrop() == true){ uint256 _prize; if (_eth >= 10000000000000000000){ // <= 10 ether _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; }else if(_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // >= 1 ether and < 10 ether _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 200000000000000000000000000000000; }else if(_eth >= 100000000000000000 && _eth < 1000000000000000000){ // >= 0.1 ether and < 1 ether _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } _eventData_.compressedData += 10000000000000000000000000000000; _eventData_.compressedData += _prize * 1000000000000000000000000000000000; airDropTracker_ = 0; } } _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); endTx(_pID, _team, _eth, _keys, _eventData_); } } function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { // round_[_rIDlast].mask * plyrRnds_[_pID][_rIDlast].keys / 1000000000000000000 - plyrRnds_[_pID][_rIDlast].mask return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256){ uint256 _now = now; //if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; //if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } /** interface : PlayerBookReceiverInterface */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "Called from PlayerBook only"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "Called from PlayerBook only"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** 识别玩家 */ function determinePID(NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0){ _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != ""){ pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return _eventData_ ; } /** 识别团队,默认是玩蛇队 */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } function managePlayer(uint256 _pID, NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; _eventData_.compressedData = _eventData_.compressedData + 10; return _eventData_ ; } /** 这轮游戏结束 */ function endRound(NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) { uint256 _rID = rID_; uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount // Fixed by Huwei //uint256 _pot = round_[_rID].pot; uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres); // 赢家获取奖池的48% uint256 _win = (_pot.mul(48)) / 100; // 社区基金获取2% uint256 _com = (_pot / 50); // 这轮游戏玩家获取的奖金 uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; // NT基金获取的奖金 uint256 _nt = (_pot.mul(potSplit_[_winTID].nt)) / 100; // 剩下的奖金 uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_nt); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0){ _gen = _gen.sub(_dust); _res = _res.add(_dust); } plyr_[_winPID].win = _win.add(plyr_[_winPID].win); if(address(communityAddr_)!=address(0x0)) { // 将社区基金奖金发到社区奖金地址 communityAddr_.transfer(_com); _com = 0 ; }else{ // 如果没有设置社区地址,那么资金分给下一轮 _res = SafeMath.add(_res,_com); _com = 0 ; } if(_nt > 0) { if(address(NTFoundationAddr_) != address(0x0)) { // 分配NT基金奖金 NTFoundationAddr_.transfer(_nt); }else{ // 如果没有设定,那么资金计入下一轮 _res = SafeMath.add(_res,_nt); _nt = 0 ; } } round_[_rID].mask = _ppt.add(round_[_rID].mask); _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.NTAmount = 0; _eventData_.newPot = _res; // 下一轮 rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndMax_); //round_[_rID].end = now.add(rndInit_).add(rndGap_); // Fixed by Huwei //round_[_rID].pot = _res; round_[_rID].prevres = _res; return(_eventData_); } function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0){ plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } function updateTimer(uint256 _keys, uint256 _rID) private { uint256 _now = now; uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** 计算空投小奖池 */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** 社区基金 奖池互换 分享 空投 */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_) private returns(NTech3DDatasets.EventReturns){ // 社区基金2%, 如果没有设置社区基金,则这份空投到用户地址 uint256 _com = _eth / 50; // 奖池互换,如果没有设置,进入到社区基金 uint256 _long = _eth / 100; if(address(otherNTech3D_)!=address(0x0)){ otherNTech3D_.potSwap.value(_long)(); }else{ _com = _com.add(_long); } // 分享,如果没有分享,进入到社区基金 uint256 _aff = _eth / 10; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit onAffiliatePayout( _affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now ); } else { _com = _com.add(_aff); } // 空投(如果没有设置社区基金地址,那么放入空投) uint256 _nt = (_eth.mul(fees_[_team].nt)).div(100); if(_com>0){ if(address(communityAddr_)!=address(0x0)) { communityAddr_.transfer(_com); }else{ _nt = _nt.add(_com); } } if(_nt > 0 ){ // amount = _nt * ntOf1Ether_ ; uint256 amount = _nt.mul(ntOf1Ether_); _eventData_.NTAmount = amount.add(_eventData_.NTAmount); NTToken_.transfer(msg.sender,amount); // address(NTTokenSeller_).transfer(_nt); } return (_eventData_) ; } /** 奖池互换 */ function potSwap() external payable { // 奖池互换放入下一轮 uint256 _rID = rID_ + 1; // Fixed by Huwei //round_[_rID].pot = round_[_rID].pot.add(msg.value); round_[_rID].prevres = round_[_rID].prevres.add(msg.value); emit onPotSwapDeposit( _rID, msg.value ); } /** 持有者 空投小奖池 终极奖池 */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, NTech3DDatasets.EventReturns memory _eventData_) private returns(NTech3DDatasets.EventReturns) { // 持有者的份额 uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // 空投小奖池 1% uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // 14% = 2% 社区 + 10% 佣金 + 1% 奖池互换 + 1% 空投小奖池 _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].nt)) / 100)); // 奖池 uint256 _pot = _eth.sub(_gen); uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** 撤退时的收益 */ function withdrawEarnings(uint256 _pID) private returns(uint256) { updateGenVault(_pID, plyr_[_pID].lrnd); uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0){ plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** 完成交易 */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, NTech3DDatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit onEndTx( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.NTAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } }
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, NTech3DDatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit onReLoadAndDistribute( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.NTAmount, _eventData_.genAmount ); } }
386,502
pragma solidity ^0.4.24; contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); event onAirPot( uint256 roundID, uint256 potType, address winner, uint256 prize ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address private owner = 0x0c204d9C438553a107B29cdE1d1e7954673b29B3; address private opAddress = 0x0c204d9C438553a107B29cdE1d1e7954673b29B3; address private comAddress = 0x24D160101C72c035287f772a8ac2b744a477F489; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x0f717ffff71e639636fcdd33727ee8c17c4724bf); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D Long Official"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 0;//extSettings.getLongExtra(); // length of the very first ICO //uint256 private rndGap_ = 0 hours ;// extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 2 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 2 hours; // max length a round timer can be uint256 constant private comDropGap_ = 24 hours; uint256 constant private rndNTR_ = 168 hours; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropPot2_; uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public airDropTracker2_ = 0; uint256 public rID_; // round id number / total rounds that have happened uint256 public comReWards_; uint256 public comAirDrop_; //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) mapping (uint256 => uint256) public inviteCount_; mapping (address => bool) public addrLock_; //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id mapping (uint256 => uint256[10]) public lastTen_; mapping (uint256 => uint256) public roundBetCount_; //rId => team => datetime mapping (uint256 => mapping (uint256 =>uint256)) public comDropLastTime_; //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. //not p3d change to owner 20% fees_[0] = F3Ddatasets.TeamFee(48,0);//(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(33,0);//(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(18,0);//(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // fees_[3] = F3Ddatasets.TeamFee(51,0);//(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(10,20);//(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(5,20); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20);//(20,20); //48% to winner, 10% to next round, 2% to com // potSplit_[3] = F3Ddatasets.PotSplit(40,20);//(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } /* modifier locked() { require(!addrLock_[msg.sender],"this address is locked"); _; }*/ //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() //locked() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() //locked() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() //locked() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() //locked() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() //locked() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() //locked() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() //locked() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt ) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt ).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders // if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; lastTen_[_rID][roundBetCount_[_rID] % 10] = _pID; roundBetCount_[_rID]++; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; emit onAirPot(_rID,1,plyr_[_pID].addr,_prize); // reset air drop tracker airDropTracker_ = 0; } } if (_eth >= 500000000000000000 && round_[_rID].pot >=100000000000000000000){ air2( _rID, _pID, _affID); } if(inviteCount_[_pID] >= 100 && (comDropLastTime_[_rID][_team] + comDropGap_) <= now){ comDrop(_rID,_pID,_affID,_team); } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } function air2(uint256 _rID, uint256 _pID, uint256 _affID) private { // airDrop2 // uint256 compressedData = 0; airDropTracker2_++; if (airdrop2() == true) { // gib muni uint256 _prize2; // calculate prize and give it to winner _prize2 = ((airDropPot2_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize2.mul(80) / 100); uint256 _affIDUp = plyr_[_affID].laff; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].win = (plyr_[_affIDUp].win).add(_prize2.mul(20) / 100); }else{ _prize2 = (_prize2.mul(80) / 100); } // adjust airDropPot2 airDropPot2_ = (airDropPot2_).sub(_prize2); // let event know a tier 3 prize was won // compressedData = 300000000000000000000000000000000; // set airdrop happened bool to true // compressedData += 10000000000000000000000000000000; // let event know how much was won // compressedData += _prize2 * 1000000000000000000000000000000000; emit onAirPot(_rID,2,plyr_[_pID].addr,_prize2); // reset air drop tracker airDropTracker2_ = 0; } // return compressedData; } function comDrop(uint256 _rID, uint256 _pID, uint256 _affID, uint256 _team) private { // uint256 compressedData = 0; uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) ))); if((seed - ((seed / 100) * 100)) < 15){ // calculate prize and give it to winner uint256 _prize3 = comAirDrop_ / 10; plyr_[_pID].win = (plyr_[_pID].win).add(_prize3.mul(2)); uint256 _affIDUp = plyr_[_affID].laff; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].win = (plyr_[_affIDUp].win).add(_prize3); _prize3 = _prize3.mul(3) ; }else{ _prize3 = _prize3.mul(2) ; } comAirDrop_ = (comAirDrop_).sub(_prize3); // let event know a tier 3 prize was won // compressedData = 300000000000000000000000000000000; // set airdrop happened bool to true // compressedData += 10000000000000000000000000000000; // let event know how much was won // compressedData += _prize3 * 1000000000000000000000000000000000; emit onAirPot(_rID,3,plyr_[_pID].addr,_prize3); comDropLastTime_[_rID][_team] = now; } // return compressedData; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 2) return(0); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; // community rewards uint256 _com = (_pot / 50); //uint256 _comTotal = ; comAddress.transfer(_com.add(comAirDrop_).add(comReWards_).add(airDropPot_).add(airDropPot2_)); comAirDrop_ = 0; comReWards_ = 0; airDropPot_ = 0; airDropPot2_ = 0; uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner //plyr_[_winPID].win = _win.add(plyr_[_winPID].win); //last ten share shareLastTen( _rID, _win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies //if (_p3d > 0) opAddress.transfer(_p3d); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now.add(comDropGap_); round_[_rID].end = now.add(comDropGap_).add(rndInit_); round_[_rID].pot = _res; return(_eventData_); } function shareLastTen(uint256 _rID, uint256 _win) private { if(roundBetCount_[_rID] >= 10){ uint256 _singleWin = _win / 10; plyr_[lastTen_[_rID][0]].win = _singleWin.add(plyr_[lastTen_[_rID][0]].win); plyr_[lastTen_[_rID][1]].win = _singleWin.add(plyr_[lastTen_[_rID][1]].win); plyr_[lastTen_[_rID][2]].win = _singleWin.add(plyr_[lastTen_[_rID][2]].win); plyr_[lastTen_[_rID][3]].win = _singleWin.add(plyr_[lastTen_[_rID][3]].win); plyr_[lastTen_[_rID][4]].win = _singleWin.add(plyr_[lastTen_[_rID][4]].win); plyr_[lastTen_[_rID][5]].win = _singleWin.add(plyr_[lastTen_[_rID][5]].win); plyr_[lastTen_[_rID][6]].win = _singleWin.add(plyr_[lastTen_[_rID][6]].win); plyr_[lastTen_[_rID][7]].win = _singleWin.add(plyr_[lastTen_[_rID][7]].win); plyr_[lastTen_[_rID][8]].win = _singleWin.add(plyr_[lastTen_[_rID][8]].win); plyr_[lastTen_[_rID][9]].win = _singleWin.add(plyr_[lastTen_[_rID][9]].win); } else{ uint256 _avarageWin = _win / roundBetCount_[_rID]; for(uint256 _index = 0; _index < roundBetCount_[_rID] ; _index++ ){ plyr_[lastTen_[_rID][_index]].win = _avarageWin.add(plyr_[lastTen_[_rID][_index]].win); } } } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); if(round_[_rID].strt.add(rndNTR_) >= now){ // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } function airdrop2() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add //(block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker2_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _p3d = 0; uint256 opEth = _eth.mul(18) / 100; opAddress.transfer(opEth); // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered _p3d = affsend( _affID, _pID, _rID, _eth, _p3d); // pay out p3d //_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract //change to owner //Divies.deposit.value(_p3d)(); owner.transfer(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function affsend(uint256 _affID, uint256 _pID, uint256 _rID, uint256 _eth, uint256 _p3d) private returns(uint256) { // distribute share to affiliate 10% uint256 _aff = _eth / 10; // distribute share to affiliate 3% uint256 _affUp = _eth.mul(3) / 100; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); uint256 _affIDUp = plyr_[_affID].laff; inviteCount_[_affID] ++; if (_affIDUp !=0 && _affIDUp != _pID && plyr_[_affIDUp].name != '') { plyr_[_affIDUp].aff = _affUp.add(plyr_[_affIDUp].aff); emit F3Devents.onAffiliatePayout(_affIDUp, plyr_[_affIDUp].addr, plyr_[_affIDUp].name, _rID, _pID, _affUp, now); inviteCount_[_affIDUp] ++; }else{ _p3d = _p3d.add(_affUp); } } else { _p3d = _aff; } return _p3d; } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { //1. pay 2% out to community rewards comReWards_ = comReWards_.add(_eth / 50); comAirDrop_ = comAirDrop_.add(_eth / 100); // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // toss 10% into airdrop2 pot airDropPot2_ = airDropPot2_.add(_eth / 10); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(39)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == owner , "only team just can activate" ); // make sure that its been linked. //require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ ; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
converts all incoming ethereum to keys. -functionhash- 0x8f38f309 (using ID for affiliate) -functionhash- 0x98a0871d (using address for affiliate) -functionhash- 0xa65b37a1 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for?/locked() set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz
{ F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) function() isActivated() isHuman() isWithinLimits(msg.value) public payable } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { _affCode = plyr_[_pID].laff; plyr_[_pID].laff = _affCode; } } else if (_affCode != plyr_[_pID].laff) { _team = verifyTeam(_team); buyCore(_pID, _affCode, _team, _eventData_); }
11,990,436
./full_match/1/0xcb6Ea7fddFdf2AFc2Bc6Bf715185A33F8E27B96b/sources/@pendle/core-v2/contracts/router/base/MarketApproxLib.sol
all safe since totalPt and totalSy is int128
function calcSyIn( MarketState memory market, MarketPreCompute memory comp, PYIndex index, uint256 netPtOut ) internal pure returns (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyIn, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade( comp, index, int256(netPtOut) ); netSyIn = uint256(-_netSyIn); netSyFee = uint256(_netSyFee); netSyToReserve = uint256(_netSyToReserve); }
3,061,560
./full_match/3/0x748159f519d17c4612483756ae02BDd1B2f3e76B/sources/github/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
See {IERC20-totalSupply}./
function totalSupply() public view virtual override returns (uint256) { return 1000000000000; }
8,265,746
//Address: 0x2ef8dcdecd124660c8cc8e55114f615c2e657da6 //Contract name: OsherCrowdsale //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.18; contract OsherCrowdsaleCore { function crowdsale( address _address )payable; function precrowdsale( address _address )payable; } contract OsherCrowdsale { address public owner; bool public crowdSaleStarted; bool public crowdSaleClosed; bool public crowdSalePause; uint public crowdSaleStartTime; uint public preicostarted; uint public deadline; address public CoreAddress; OsherCrowdsaleCore core; modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function OsherCrowdsale(){ crowdSaleStarted = false; crowdSaleClosed = false; crowdSalePause = false; preicostarted = now; owner = msg.sender; } // fallback function to receive all incoming ether funds and then forwarded to the DragonCrowdsaleCore contract function () payable { require ( crowdSaleClosed == false && crowdSalePause == false ); if ( crowdSaleStarted ) { require ( now < deadline ); core.crowdsale.value( msg.value )( msg.sender); } else { core.precrowdsale.value( msg.value )( msg.sender); } } // Start this to initiate crowdsale - will run for 60 days function startCrowdsale() onlyOwner { crowdSaleStarted = true; crowdSaleStartTime = now; deadline = now + 60 days; } //terminates the crowdsale function endCrowdsale() onlyOwner { crowdSaleClosed = true; } //pauses the crowdsale function pauseCrowdsale() onlyOwner { crowdSalePause = true; } //unpauses the crowdsale function unpauseCrowdsale() onlyOwner { crowdSalePause = false; } // set the dragon crowdsalecore contract function setCore( address _core ) onlyOwner { require ( _core != 0x00 ); CoreAddress = _core; core = OsherCrowdsaleCore( _core ); } function transferOwnership( address _address ) onlyOwner { require ( _address!= 0x00 ); owner = _address ; } }
Start this to initiate crowdsale - will run for 60 days
function startCrowdsale() onlyOwner { crowdSaleStarted = true; crowdSaleStartTime = now; deadline = now + 60 days; }
13,070,102
pragma solidity ^0.5.11; // Public-Sale for #3277-12000 stage of Voken2.0 // // More info: // https://vision.network // https://voken.io // // Contact us: // support@vision.network // support@voken.io /** * @dev Uint256 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath256 { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Uint16 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). */ function sub(uint16 a, uint16 b) internal pure returns (uint16) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. */ function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. */ function div(uint16 a, uint16 b) internal pure returns (uint16) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. */ function mod(uint16 a, uint16 b) internal pure returns (uint16) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. */ contract Ownable { address internal _owner; address internal _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event OwnershipAccepted(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the addresses of the current and new owner. */ function owner() public view returns (address currentOwner, address newOwner) { currentOwner = _owner; newOwner = _newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner(address account) public view returns (bool) { return account == _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * IMPORTANT: Need to run {acceptOwnership} by the new owner. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _newOwner = newOwner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Accept ownership of the contract. * * Can only be called by the new owner. */ function acceptOwnership() public { require(msg.sender == _newOwner, "Ownable: caller is not the new owner address"); require(msg.sender != address(0), "Ownable: caller is the zero address"); emit OwnershipAccepted(_owner, msg.sender); _owner = msg.sender; _newOwner = address(0); } /** * @dev Rescue compatible ERC20 Token * * Can only be called by the current owner. */ function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(recipient != address(0), "Rescue: recipient is the zero address"); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount, "Rescue: amount exceeds balance"); _token.transfer(recipient, amount); } /** * @dev Withdraw Ether * * Can only be called by the current owner. */ function withdrawEther(address payable recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Withdraw: recipient is the zero address"); uint256 balance = address(this).balance; require(balance >= amount, "Withdraw: amount exceeds balance"); recipient.transfer(amount); } } /** * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { bool private _paused; event Paused(address account); event Unpaused(address account); /** * @dev Constructor */ constructor () internal { _paused = false; } /** * @return Returns true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Paused"); _; } /** * @dev Sets paused state. * * Can only be called by the current owner. */ function setPaused(bool value) external onlyOwner { _paused = value; if (_paused) { emit Paused(msg.sender); } else { emit Unpaused(msg.sender); } } } /** * @dev Part of ERC20 interface. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } /** * @title Voken2.0 interface. */ interface IVoken2 { function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool); function whitelisted(address account) external view returns (bool); function whitelistReferee(address account) external view returns (address payable); function whitelistReferralsCount(address account) external view returns (uint256); } /** * @dev Interface of an allocation contract */ interface IAllocation { function reservedOf(address account) external view returns (uint256); } /** * @dev Allocation for VOKEN */ library Allocations { struct Allocation { uint256 amount; uint256 timestamp; } } /** * @title VokenShareholders interface. */ interface VokenShareholders { // } /** * @title Voken Public Sale v2.0 */ contract VokenPublicSale2 is Ownable, Pausable, IAllocation { using SafeMath16 for uint16; using SafeMath256 for uint256; using Roles for Roles.Role; using Allocations for Allocations.Allocation; // Proxy Roles.Role private _proxies; // Addresses IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB); VokenShareholders private _SHAREHOLDERS = VokenShareholders(0x7712F76D2A52141D44461CDbC8b660506DCAB752); address payable private _TEAM; // Referral rewards, 35% for 15 levels uint16[15] private REWARDS_PCT = [6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]; // Limit uint16[] private LIMIT_COUNTER = [1, 3, 10, 50, 100, 200, 300]; uint256[] private LIMIT_WEIS = [100 ether, 50 ether, 40 ether, 30 ether, 20 ether, 10 ether, 5 ether]; uint256 private LIMIT_WEI_MIN = 3 ether; // 6,000 000 gas mininum uint24 private GAS_MIN = 6000000; // Price uint256 private VOKEN_USD_PRICE_START = 1000; // $ 0.00100 USD uint256 private VOKEN_USD_PRICE_STEP = 10; // $ + 0.00001 USD uint256 private STAGE_USD_CAP_START = 100000000; // $ 100 USD uint256 private STAGE_USD_CAP_STEP = 1000000; // $ +1 USD uint256 private STAGE_USD_CAP_MAX = 15100000000; // $ 15,100 USD // 1 Ether|Voken = xx.xxxxxx USD, with 6 decimals uint256 private _etherUsdPrice; uint256 private _vokenUsdPrice; // Progress uint16 private SEASON_MAX = 100; // 100 seasons max uint16 private SEASON_LIMIT = 20; // 20 season total uint16 private SEASON_STAGES = 600; // each 600 stages is a season uint16 private STAGE_MAX = SEASON_STAGES.mul(SEASON_MAX); uint16 private STAGE_LIMIT = SEASON_STAGES.mul(SEASON_LIMIT); uint16 private _stage; uint16 private _season; // Sum uint256 private _txs; uint256 private _vokenIssued; uint256 private _vokenIssuedTxs; uint256 private _vokenBonus; uint256 private _vokenBonusTxs; uint256 private _weiSold; uint256 private _weiRewarded; uint256 private _weiShareholders; uint256 private _weiTeam; uint256 private _weiPended; uint256 private _usdSold; uint256 private _usdRewarded; // Shareholders ratio uint256 private SHAREHOLDERS_RATIO_START = 15000000; // 15%, with 8 decimals uint256 private SHAREHOLDERS_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals uint256 private _shareholdersRatio; // Cache bool private _cacheWhitelisted; uint256 private _cacheWeiShareholders; uint256 private _cachePended; uint16[] private _cacheRewards; address payable[] private _cacheReferees; // Allocations mapping (address => Allocations.Allocation[]) private _allocations; // Account mapping (address => uint256) private _accountVokenIssued; mapping (address => uint256) private _accountVokenBonus; mapping (address => uint256) private _accountVokenReferral; mapping (address => uint256) private _accountVokenReferrals; mapping (address => uint256) private _accountUsdPurchased; mapping (address => uint256) private _accountWeiPurchased; mapping (address => uint256) private _accountUsdRewarded; mapping (address => uint256) private _accountWeiRewarded; // Stage mapping (uint16 => uint256) private _stageUsdSold; mapping (uint16 => uint256) private _stageVokenIssued; mapping (uint16 => uint256) private _stageVokenBonus; // Season mapping (uint16 => uint256) private _seasonWeiSold; mapping (uint16 => uint256) private _seasonWeiRewarded; mapping (uint16 => uint256) private _seasonWeiShareholders; mapping (uint16 => uint256) private _seasonWeiPended; mapping (uint16 => uint256) private _seasonUsdSold; mapping (uint16 => uint256) private _seasonUsdRewarded; mapping (uint16 => uint256) private _seasonUsdShareholders; mapping (uint16 => uint256) private _seasonVokenIssued; mapping (uint16 => uint256) private _seasonVokenBonus; // Account in season mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountIssued; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountBonus; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferral; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountRewarded; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRewarded; // Season wei limit accounts mapping (uint16 => mapping (uint256 => address[])) private _seasonLimitAccounts; mapping (uint16 => address[]) private _seasonLimitWeiMinAccounts; // Referrals mapping (uint16 => address[]) private _seasonAccounts; mapping (uint16 => address[]) private _seasonReferrals; mapping (uint16 => mapping (address => bool)) private _seasonHasAccount; mapping (uint16 => mapping (address => bool)) private _seasonHasReferral; mapping (uint16 => mapping (address => address[])) private _seasonAccountReferrals; mapping (uint16 => mapping (address => mapping (address => bool))) private _seasonAccountHasReferral; // Events event ProxyAdded(address indexed account); event ProxyRemoved(address indexed account); event StageClosed(uint256 _stageNumber); event SeasonClosed(uint16 _seasonNumber); event AuditEtherPriceUpdated(uint256 value, address indexed account); event Log(uint256 value); /** * @dev Throws if called by account which is not a proxy. */ modifier onlyProxy() { require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role"); _; } /** * @dev Returns true if the `account` has the Proxy role. */ function isProxy(address account) public view returns (bool) { return _proxies.has(account); } /** * @dev Give an `account` access to the Proxy role. * * Can only be called by the current owner. */ function addProxy(address account) public onlyOwner { _proxies.add(account); emit ProxyAdded(account); } /** * @dev Remove an `account` access from the Proxy role. * * Can only be called by the current owner. */ function removeProxy(address account) public onlyOwner { _proxies.remove(account); emit ProxyRemoved(account); } /** * @dev Returns the VOKEN address. */ function VOKEN() public view returns (IVoken2) { return _VOKEN; } /** * @dev Returns the shareholders contract address. */ function SHAREHOLDERS() public view returns (VokenShareholders) { return _SHAREHOLDERS; } /** * @dev Returns the team wallet address. */ function TEAM() public view returns (address) { return _TEAM; } /** * @dev Returns the main status. */ function status() public view returns (uint16 stage, uint16 season, uint256 etherUsdPrice, uint256 vokenUsdPrice, uint256 shareholdersRatio) { if (_stage > STAGE_MAX) { stage = STAGE_MAX; season = SEASON_MAX; } else { stage = _stage; season = _season; } etherUsdPrice = _etherUsdPrice; vokenUsdPrice = _vokenUsdPrice; shareholdersRatio = _shareholdersRatio; } /** * @dev Returns the sum. */ function sum() public view returns(uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiTeam, uint256 weiPended, uint256 usdSold, uint256 usdRewarded) { vokenIssued = _vokenIssued; vokenBonus = _vokenBonus; weiSold = _weiSold; weiRewarded = _weiRewarded; weiShareholders = _weiShareholders; weiTeam = _weiTeam; weiPended = _weiPended; usdSold = _usdSold; usdRewarded = _usdRewarded; } /** * @dev Returns the transactions' counter. */ function transactions() public view returns(uint256 txs, uint256 vokenIssuedTxs, uint256 vokenBonusTxs) { txs = _txs; vokenIssuedTxs = _vokenIssuedTxs; vokenBonusTxs = _vokenBonusTxs; } /** * @dev Returns the `account` data. */ function queryAccount(address account) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiRewarded, uint256 usdPurchased, uint256 usdRewarded) { vokenIssued = _accountVokenIssued[account]; vokenBonus = _accountVokenBonus[account]; vokenReferral = _accountVokenReferral[account]; vokenReferrals = _accountVokenReferrals[account]; weiPurchased = _accountWeiPurchased[account]; weiRewarded = _accountWeiRewarded[account]; usdPurchased = _accountUsdPurchased[account]; usdRewarded = _accountUsdRewarded[account]; } /** * @dev Returns the stage data by `stageIndex`. */ function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice, uint256 shareholdersRatio, uint256 vokenIssued, uint256 vokenBonus, uint256 vokenCap, uint256 vokenOnSale, uint256 usdSold, uint256 usdCap, uint256 usdOnSale) { if (stageIndex <= STAGE_LIMIT) { vokenUsdPrice = _calcVokenUsdPrice(stageIndex); shareholdersRatio = _calcShareholdersRatio(stageIndex); vokenIssued = _stageVokenIssued[stageIndex]; vokenBonus = _stageVokenBonus[stageIndex]; vokenCap = _stageVokenCap(stageIndex); vokenOnSale = vokenCap.sub(vokenIssued); usdSold = _stageUsdSold[stageIndex]; usdCap = _stageUsdCap(stageIndex); usdOnSale = usdCap.sub(usdSold); } } /** * @dev Returns the season data by `seasonNumber`. */ function season(uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiPended, uint256 usdSold, uint256 usdRewarded, uint256 usdShareholders) { if (seasonNumber <= SEASON_LIMIT) { vokenIssued = _seasonVokenIssued[seasonNumber]; vokenBonus = _seasonVokenBonus[seasonNumber]; weiSold = _seasonWeiSold[seasonNumber]; weiRewarded = _seasonWeiRewarded[seasonNumber]; weiShareholders = _seasonWeiShareholders[seasonNumber]; weiPended = _seasonWeiPended[seasonNumber]; usdSold = _seasonUsdSold[seasonNumber]; usdRewarded = _seasonUsdRewarded[seasonNumber]; usdShareholders = _seasonUsdShareholders[seasonNumber]; } } /** * @dev Returns the `account` data of #`seasonNumber` season. */ function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiReferrals, uint256 weiRewarded, uint256 usdPurchased, uint256 usdReferrals, uint256 usdRewarded) { if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) { vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account]; vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account]; vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account]; vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account]; weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account]; weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account]; weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account]; usdPurchased = _usdSeasonAccountPurchased[seasonNumber][account]; usdReferrals = _usdSeasonAccountReferrals[seasonNumber][account]; usdRewarded = _usdSeasonAccountRewarded[seasonNumber][account]; } } /** * @dev Referral accounts in a season by `seasonNumber`. */ function seasonReferrals(uint16 seasonNumber) public view returns (address[] memory) { return _seasonReferrals[seasonNumber]; } /** * @dev Referral accounts in a season by `seasonNumber` of `account`. */ function seasonAccountReferrals(uint16 seasonNumber, address account) public view returns (address[] memory) { return _seasonAccountReferrals[seasonNumber][account]; } /** * @dev Voken price in USD, by `stageIndex`. */ function _calcVokenUsdPrice(uint16 stageIndex) private view returns (uint256) { return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex)); } /** * @dev Returns the shareholders ratio by `stageIndex`. */ function _calcShareholdersRatio(uint16 stageIndex) private view returns (uint256) { return SHAREHOLDERS_RATIO_START.add(SHAREHOLDERS_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX)); } /** * @dev Returns the dollor cap of `stageIndex`. */ function _stageUsdCap(uint16 stageIndex) private view returns (uint256) { uint256 __usdCap = STAGE_USD_CAP_START.add(STAGE_USD_CAP_STEP.mul(stageIndex)); if (__usdCap > STAGE_USD_CAP_MAX) { return STAGE_USD_CAP_MAX; } return __usdCap; } /** * @dev Returns the Voken cap of `stageIndex`. */ function _stageVokenCap(uint16 stageIndex) private view returns (uint256) { return _stageUsdCap(stageIndex).mul(1000000).div(_calcVokenUsdPrice(stageIndex)); } /** * @dev Returns an {uint256} by `value` * _shareholdersRatio / 100000000 */ function _2shareholders(uint256 value) private view returns (uint256) { return value.mul(_shareholdersRatio).div(100000000); } /** * @dev wei => USD, by `weiAmount`. */ function _wei2usd(uint256 weiAmount) private view returns (uint256) { return weiAmount.mul(_etherUsdPrice).div(1 ether); } /** * @dev USD => wei, by `usdAmount`. */ function _usd2wei(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1 ether).div(_etherUsdPrice); } /** * @dev USD => voken, by `usdAmount`. */ function _usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); } /** * @dev Returns the season number by `stageIndex`. */ function _seasonNumber(uint16 stageIndex) private view returns (uint16) { if (stageIndex > 0) { uint16 __seasonNumber = stageIndex.div(SEASON_STAGES); if (stageIndex.mod(SEASON_STAGES) > 0) { return __seasonNumber.add(1); } return __seasonNumber; } return 1; } /** * Close the current stage. */ function _closeStage() private { _stage = _stage.add(1); emit StageClosed(_stage); // Close current season uint16 __seasonNumber = _seasonNumber(_stage); if (_season < __seasonNumber) { _season = __seasonNumber; emit SeasonClosed(_season); } _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); } /** * @dev Update audit ether price. */ function updateEtherUsdPrice(uint256 value) external onlyProxy { _etherUsdPrice = value; emit AuditEtherPriceUpdated(value, msg.sender); } /** * @dev Update team wallet address. */ function updateTeamWallet(address payable account) external onlyOwner { _TEAM = account; } /** * @dev Returns current max wei value. */ function weiMax() public view returns (uint256) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (_seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return LIMIT_WEIS[i]; } } return LIMIT_WEI_MIN; } /** * @dev Returns the {limitIndex} and {weiMax}. */ function _limit(uint256 weiAmount) private view returns (uint256 __wei) { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { return 0; } if (__purchased < LIMIT_WEIS[i]) { __wei = LIMIT_WEIS[i].sub(__purchased); if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return __wei; } } } if (__purchased < LIMIT_WEI_MIN) { return LIMIT_WEI_MIN.sub(__purchased); } } /** * @dev Updates the season limit accounts, or wei min accounts. */ function _updateSeasonLimits() private { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; if (__purchased > LIMIT_WEI_MIN) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { _seasonLimitAccounts[_season][i].push(msg.sender); return; } } } else if (__purchased == LIMIT_WEI_MIN) { _seasonLimitWeiMinAccounts[_season].push(msg.sender); return; } } /** * @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`. */ function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) { if (limitIndex < LIMIT_WEIS.length) { weis = LIMIT_WEIS[limitIndex]; accounts = _seasonLimitAccounts[seasonNumber][limitIndex]; } else { weis = LIMIT_WEI_MIN; accounts = _seasonLimitWeiMinAccounts[seasonNumber]; } } /** * @dev constructor */ constructor () public { _stage = 3277; _season = _seasonNumber(_stage); _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); _TEAM = msg.sender; addProxy(msg.sender); } /** * @dev Receive ETH, and excute the exchange. */ function () external payable whenNotPaused { require(_etherUsdPrice > 0, "VokenPublicSale2: Audit ETH price is zero"); require(_stage <= STAGE_MAX, "VokenPublicSale2: Voken Public-Sale Completled"); uint256 __usdAmount; uint256 __usdRemain; uint256 __usdUsed; uint256 __weiUsed; uint256 __voken; // Limit uint256 __weiMax = _limit(msg.value); if (__weiMax < msg.value) { __usdAmount = _wei2usd(__weiMax); } else { __usdAmount = _wei2usd(msg.value); } __usdRemain = __usdAmount; if (__usdRemain > 0) { // cache _cache(); // USD => Voken while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = _tx(__usdRemain); __voken = __voken.add(__txVokenIssued); } // Used __usdUsed = __usdAmount.sub(__usdRemain); __weiUsed = _usd2wei(__usdUsed); // Whitelist if (_cacheWhitelisted && __voken > 0) { _mintVokenBonus(__voken); for(uint16 i = 0; i < _cacheReferees.length; i++) { address payable __referee = _cacheReferees[i]; uint256 __usdReward = __usdUsed.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __weiUsed.mul(_cacheRewards[i]).div(100); __referee.transfer(__weiReward); _usdRewarded = _usdRewarded.add(__usdReward); _weiRewarded = _weiRewarded.add(__weiReward); _accountUsdRewarded[__referee] = _accountUsdRewarded[__referee].add(__usdReward); _accountWeiRewarded[__referee] = _accountWeiRewarded[__referee].add(__weiReward); } if (_cachePended > 0) { _weiPended = _weiPended.add(__weiUsed.mul(_cachePended).div(100)); } } // Counter if (__weiUsed > 0) { _txs = _txs.add(1); _usdSold = _usdSold.add(__usdUsed); _weiSold = _weiSold.add(__weiUsed); _accountUsdPurchased[msg.sender] = _accountUsdPurchased[msg.sender].add(__usdUsed); _accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed); // Wei for SHAREHOLDERS _weiShareholders = _weiShareholders.add(_cacheWeiShareholders); (bool __bool,) = address(_SHAREHOLDERS).call.value(_cacheWeiShareholders)(""); assert(__bool); // Wei for TEAM uint256 __weiTeam = _weiSold.sub(_weiRewarded).sub(_weiShareholders).sub(_weiPended).sub(_weiTeam); _weiTeam = _weiTeam.add(__weiTeam); _TEAM.transfer(__weiTeam); // Update season limits _updateSeasonLimits(); } // Reset cache _resetCache(); } // If wei remains, refund. uint256 __weiRemain = msg.value.sub(__weiUsed); if (__weiRemain > 0) { msg.sender.transfer(__weiRemain); } } /** * @dev Cache. */ function _cache() private { if (!_seasonHasAccount[_season][msg.sender]) { _seasonAccounts[_season].push(msg.sender); _seasonHasAccount[_season][msg.sender] = true; } _cacheWhitelisted = _VOKEN.whitelisted(msg.sender); if (_cacheWhitelisted) { address __account = msg.sender; for(uint16 i = 0; i < REWARDS_PCT.length; i++) { address __referee = _VOKEN.whitelistReferee(__account); if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) { if (!_seasonHasReferral[_season][__referee]) { _seasonReferrals[_season].push(__referee); _seasonHasReferral[_season][__referee] = true; } if (!_seasonAccountHasReferral[_season][__referee][__account]) { _seasonAccountReferrals[_season][__referee].push(__account); _seasonAccountHasReferral[_season][__referee][__account] = true; } _cacheReferees.push(address(uint160(__referee))); _cacheRewards.push(REWARDS_PCT[i]); } else { _cachePended = _cachePended.add(REWARDS_PCT[i]); } __account = __referee; } } } /** * @dev Reset cache. */ function _resetCache() private { delete _cacheWeiShareholders; if (_cacheWhitelisted) { delete _cacheWhitelisted; delete _cacheReferees; delete _cacheRewards; delete _cachePended; } } /** * @dev USD => Voken */ function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) { uint256 __stageUsdCap = _stageUsdCap(_stage); uint256 __usdUsed; // in stage if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) { __usdUsed = __usd; (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); // close stage, if stage dollor cap reached if (__stageUsdCap == _stageUsdSold[_stage]) { _closeStage(); } } // close stage else { __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]); (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); _closeStage(); __usdRemain = __usd.sub(__usdUsed); } } /** * @dev USD => voken & wei, and make records. */ function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) { __wei = _usd2wei(__usd); __voken = _usd2voken(__usd); uint256 __usdShareholders = _2shareholders(__usd); uint256 __weiShareholders = _usd2wei(__usdShareholders); // Stage: usd _stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd); // Season: usd, wei _seasonUsdSold[_season] = _seasonUsdSold[_season].add(__usd); _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei); // Season: wei pended if (_cachePended > 0) { _seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100)); } // Season shareholders: usd, wei _seasonUsdShareholders[_season] = _seasonUsdShareholders[_season].add(__usdShareholders); _seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders); // Cache _cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders); // Season => account: usd, wei _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd); _weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei); // season referral account if (_cacheWhitelisted) { for (uint16 i = 0; i < _cacheRewards.length; i++) { address __referee = _cacheReferees[i]; uint256 __usdReward = __usd.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100); // season _seasonUsdRewarded[_season] = _seasonUsdRewarded[_season].add(__usdReward); _seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward); // season => account _usdSeasonAccountRewarded[_season][__referee] = _usdSeasonAccountRewarded[_season][__referee].add(__usdReward); _weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward); _usdSeasonAccountReferrals[_season][__referee] = _usdSeasonAccountReferrals[_season][__referee].add(__usd); _weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei); _vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken); _accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken); if (i == 0) { _vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken); _accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken); } } } } /** * @dev Mint Voken issued. */ function _mintVokenIssued(uint256 amount) private { // Global _vokenIssued = _vokenIssued.add(amount); _vokenIssuedTxs = _vokenIssuedTxs.add(1); // Account _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); // Stage _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount); // Season _seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount); _vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount); // Mint assert(_VOKEN.mint(msg.sender, amount)); } /** * @dev Mint Voken bonus. */ function _mintVokenBonus(uint256 amount) private { // Global _vokenBonus = _vokenBonus.add(amount); _vokenBonusTxs = _vokenBonusTxs.add(1); // Account _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); // Stage _stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount); // Season _seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount); _vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount); // Mint with allocation Allocations.Allocation memory __allocation; __allocation.amount = amount; __allocation.timestamp = now; _allocations[msg.sender].push(__allocation); assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this))); } /** * @dev Returns the reserved amount of VOKEN by `account`. */ function reservedOf(address account) public view returns (uint256) { Allocations.Allocation[] memory __allocations = _allocations[account]; uint256 __len = __allocations.length; if (__len > 0) { uint256 __vokenIssued = _accountVokenIssued[account]; uint256 __vokenBonus = _accountVokenBonus[account]; uint256 __vokenReferral = _accountVokenReferral[account]; uint256 __vokenBalance = _VOKEN.balanceOf(account); // balance fixed, by Voken issued. if (__vokenIssued < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenIssued); } else { __vokenBalance = 0; } // balance fixed, by Voken bonus. if (__vokenBonus < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenBonus); } else { __vokenBalance = 0; } uint256 __reserved; for (uint256 i = 0; i < __len; i++) { // Voken reserved. Allocations.Allocation memory __allocation = __allocations[i]; __reserved = __reserved.add(__allocation.amount); if (now >= __allocation.timestamp.add(90 days)) { // default: 180 days. uint256 __distance = 180 days; // shorten the distance, by Voken referral, at least 120 days. if (__vokenReferral > __allocation.amount) { __distance = __distance.sub(__vokenReferral.div(__allocation.amount).mul(1 days)); if (__distance > 120 days) { __distance = 120 days; } } // shorten the distance, by Voken holding if (__vokenBalance > __allocation.amount) { __distance = __distance.sub(__vokenBalance.div(__allocation.amount).mul(30 days)); } // at least: 90 days if (__distance > 90 days) { __distance = 90 days; } // calc reserved uint256 __timestamp = __allocation.timestamp.add(__distance); if (now > __timestamp) { uint256 __passed = now.sub(__timestamp).div(1 days).add(1); if (__passed > 30) { __reserved = __reserved.sub(__allocation.amount); } else { __reserved = __reserved.sub(__allocation.amount.mul(__passed).div(30)); } } } } return __reserved; } return 0; } }
Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`./
function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) { if (limitIndex < LIMIT_WEIS.length) { weis = LIMIT_WEIS[limitIndex]; accounts = _seasonLimitAccounts[seasonNumber][limitIndex]; } else { weis = LIMIT_WEI_MIN; accounts = _seasonLimitWeiMinAccounts[seasonNumber]; } }
14,102,021
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.9; import "@uma/core/contracts/financial-templates/common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol"; import "@uma/core/contracts/common/implementation/Lockable.sol"; /** * @title Linear Long Short Pair Financial Product Library. * @notice Adds settlement logic to create linear LSPs that have a capped percentage payable to the long (& short) token to * make market making both the long and short tokens easier in a v2 style AMM. */ contract ReserveLSPL is LongShortPairFinancialProductLibrary, Lockable { struct ReserveLinearLongShortPairParameters { uint256 upperBound; uint256 pctLongCap; } mapping(address => ReserveLinearLongShortPairParameters) public longShortPairParameters; /// `longShortPair` is not a valid LSP address. /// @param longShortPair The address of the LSP contract. error InvalidLSPAddress(address longShortPair); /// `upperBound` has to be greater than zero. /// @param upperBound The upper price that the LSP will operate within. error InvalidBound(uint256 upperBound); /// `pctLongCap` has to be less than 1 ether. /// @param pctLongCap The cap on the percentage that can be allocated to the long token - enforced for improving MM on v2 AMMs for both L&S tokens. error InvalidCap(uint256 pctLongCap); /// @notice Parameters already set for calling LSP. error ParametersSet(); /// @notice Parameters not set for calling LSP. error ParametersNotSet(); /** * @notice Enables any address to set the parameters for an associated financial product. * @param longShortPair The address of the LSP contract. * @param upperBound The upper price that the LSP will operate within. * @param pctLongCap The cap on the percentage that can be allocated to the long token - enforced for improving MM on v2 AMMs for both L&S tokens. * @dev Note: * a) Any address can set these parameters * b) existing LSP parameters for address not set. * c) upperBound > 0. * d) parameters can only be set once to prevent the deployer from changing the parameters after the fact. * e) For safety, parameters should be set before depositing any synthetic tokens in a liquidity pool. * f) longShortPair must expose an expirationTimestamp method to validate it is correctly deployed. */ function setLongShortPairParameters( address longShortPair, uint256 upperBound, uint256 pctLongCap ) public nonReentrant { if (ExpiringContractInterface(longShortPair).expirationTimestamp() == 0) revert InvalidLSPAddress(longShortPair); // upperBound at 0 would cause a division by 0 if (upperBound <= 0) revert InvalidBound(upperBound); if (pctLongCap >= 1 ether) revert InvalidCap(pctLongCap); ReserveLinearLongShortPairParameters memory params = longShortPairParameters[longShortPair]; if (params.upperBound != 0) revert ParametersSet(); longShortPairParameters[longShortPair] = ReserveLinearLongShortPairParameters({ upperBound: upperBound, pctLongCap: pctLongCap }); } /** * @notice Returns a number between 0 and 1e18 to indicate how much collateral each long and short token is entitled * to per collateralPerPair. * @param expiryPrice The price from the optimistic oracle for the LSP price identifier. * @return expiryPercentLong to indicate how much collateral should be sent between long and short tokens. */ function percentageLongCollateralAtExpiry(int256 expiryPrice) public view override nonReentrantView returns (uint256) { ReserveLinearLongShortPairParameters memory params = longShortPairParameters[msg.sender]; if (params.upperBound == 0) revert ParametersNotSet(); uint256 positivePrice = expiryPrice < 0 ? 0 : uint256(expiryPrice); uint256 effectiveUpperBound = (params.upperBound * params.pctLongCap) / 1 ether; uint256 effectiveLowerBound = (params.upperBound * (1 ether - params.pctLongCap)) / 1 ether; if (positivePrice <= effectiveLowerBound) return (1 ether - params.pctLongCap); if (positivePrice >= effectiveUpperBound) return params.pctLongCap; return (positivePrice * 1 ether) / params.upperBound; } }
Enables any address to set the parameters for an associated financial product. longShortPair The address of the LSP contract. upperBound The upper price that the LSP will operate within. pctLongCap The cap on the percentage that can be allocated to the long token - enforced for improving MM on v2 AMMs for both L&S tokens. Note: a) Any address can set these parameters b) existing LSP parameters for address not set. c) upperBound > 0. d) parameters can only be set once to prevent the deployer from changing the parameters after the fact. e) For safety, parameters should be set before depositing any synthetic tokens in a liquidity pool. f) longShortPair must expose an expirationTimestamp method to validate it is correctly deployed./ upperBound at 0 would cause a division by 0
function setLongShortPairParameters( address longShortPair, uint256 upperBound, uint256 pctLongCap ) public nonReentrant { if (ExpiringContractInterface(longShortPair).expirationTimestamp() == 0) revert InvalidLSPAddress(longShortPair); if (upperBound <= 0) revert InvalidBound(upperBound); if (pctLongCap >= 1 ether) revert InvalidCap(pctLongCap); ReserveLinearLongShortPairParameters memory params = longShortPairParameters[longShortPair]; if (params.upperBound != 0) revert ParametersSet(); longShortPairParameters[longShortPair] = ReserveLinearLongShortPairParameters({ upperBound: upperBound, pctLongCap: pctLongCap }); }
6,357,303
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IRiverBox.sol"; import "../interfaces/IRiverBoxRandom.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract RiverBoxImpl is IRiverBox, ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, OwnableUpgradeable { using StringsUpgradeable for uint256; using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; CountersUpgradeable.Counter private _tokenIds; uint16[] private _stockLocations; uint32[] private _stockSignatures; uint32 private _stockCounter; /* ================ GLOBAL CONFIGURATION ================ */ // price per box - Pawn uint256 public boxPrice; uint256 public totalClaimableAmount; string public baseURI; address public randomGeneratorAddress; mapping(uint256 => string) private _tokenURIs; mapping(uint256 => Product) private _tokenDetailsMapping; mapping(address => uint256) public paidBoxes; // number of boxes user has bought mapping(uint256 => Hierarchy) private _tokenHierarchyMapping; mapping(address => uint256) public claimableAmountMapping; mapping(address => uint256) public referrerContrib; uint256 public totalReferrerContrib; address proxyRegistryAddress; /* ================ SHARES ================ */ address public funderAddress; address public devAddress; address public marketAddress; uint8 public devShare; uint8 public marketShare; bool public fuseLock; function initialize( uint256 _boxPrice, string memory _name, string memory _symbol, string memory _initBaseURI, address _proxyRegistryAddress ) public initializer { __Ownable_init(); __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); __ERC721_init(_name, _symbol); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _pause(); fuseLock = true; boxPrice = _boxPrice; baseURI = _initBaseURI; proxyRegistryAddress = _proxyRegistryAddress; } /* ================ UTIL FUNCTIONS ================ */ function _pickLocation(uint256 index) internal returns (uint16, uint32) { uint256 lastIndex = _stockLocations.length - 1; uint16 lastStockLocation = _stockLocations[lastIndex]; uint16 locationId = _stockLocations[index]; _stockLocations[index] = lastStockLocation; _stockLocations.pop(); uint32 lastSignature = _stockSignatures[lastIndex]; uint32 signature = _stockSignatures[index]; _stockSignatures[index] = lastSignature; _stockSignatures.pop(); return (locationId, signature); } /* ================ VIEWS ================ */ function pawnsStock() public view returns (uint256) { return _stockLocations.length.sub(totalClaimableAmount); } function batchStockInfo(uint256 startIndex, uint256 length) public view returns (uint256[] memory, uint256[] memory) { require(startIndex < _stockLocations.length, "startIndex cannot over stockLocationsLength"); require(length > 0, "length cannot equal 0"); uint256 endIndex = MathUpgradeable.min(startIndex + length, _stockLocations.length); uint256 realLength = endIndex - startIndex; uint256[] memory locationIds = new uint256[](realLength); uint256[] memory signatures = new uint256[](realLength); for (uint256 idx = 0; idx < realLength; ++idx) { locationIds[idx] = _stockLocations[startIndex.add(idx)]; signatures[idx] = _stockSignatures[startIndex.add(idx)]; } return (locationIds, signatures); } /** * @dev Ultimate view for inspecting a token * @param tokenId the unique ID of a RiverMenNFT token * @return [[locationId, fusionCount, signature, creationTime, parts], ownerAddress, tokenURI, dealId] * @notice dealId = 0 means the item is not listed in exchange */ function allInfo(uint256 tokenId) public view returns ( Product memory, address, string memory ) { require(_exists(tokenId), "Token not exists"); return (_tokenDetailsMapping[tokenId], ownerOf(tokenId), tokenURI(tokenId)); } /** * @dev Get token detail information */ function tokenHierarchy(uint256 locationId) public view override returns (Hierarchy memory) { return _tokenHierarchyMapping[locationId]; } /** * @dev Get token detail information */ function tokenDetail(uint256 tokenId) public view override returns (Product memory) { require(_exists(tokenId), "Token not exists"); return _tokenDetailsMapping[tokenId]; } /** * @dev Verify if a list of parts can be used to fuse new product */ function verifyFusion(uint256[] memory tokenIds) public view override returns (bool) { if (tokenIds.length == 0) return false; require(_exists(tokenIds[0]), "Token not exists"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; if (parentLocationId == 0) return false; uint16[] memory childLocationIds = _tokenHierarchyMapping[parentLocationId].childLocationIds; if (childLocationIds.length != tokenIds.length) return false; for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; require(_exists(tokenId), "Token not exists"); if (_tokenDetailsMapping[tokenId].fusionCount > 0) return false; if (_tokenHierarchyMapping[_tokenDetailsMapping[tokenId].locationId].parentLocationId != parentLocationId) return false; if (ownerOf(tokenId) != _msgSender()) return false; // check duplicate TODO: find a more effective way and without using hash for (uint256 j = i + 1; j < tokenIds.length; ++j) { if (tokenId == tokenIds[j]) return false; } } return true; } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view override(IRiverBox, ERC721Upgradeable) returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(_tokenURI).length > 0) { return _tokenURI; } else { return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } } function implementationVersion() public pure override returns (string memory) { return "1.2.1"; } /* ================ PRIVATE FUNCTIONS ================ */ function _notContract() internal view { uint256 size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0, "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); } /** * @dev Mint a new Item * @param receiver account address to receive the new item */ function _awardItem(address receiver) private returns (uint256) { _tokenIds.increment(); uint256 newId = _tokenIds.current(); _safeMint(receiver, newId); return newId; } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address) internal view override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission to do upgrades"); } /* ================ TRANSACTIONS ================ */ /** * @dev Buy N (n<10) boxes, this function receive payment and * mint new product(s) to sender * @param quality number of boxes * @param referrer referrer account address */ function buy(uint256 quality, address referrer) external payable override whenNotPaused nonReentrant { _notContract(); require(quality <= pawnsStock(), "blind box sold out"); require(quality <= 20, "exceed maximum quality 20"); require(msg.value >= boxPrice.mul(quality), "payment is less than box price"); boxesAward(quality, _msgSender()); if (referrer != address(0)) { referrerContrib[referrer] = referrerContrib[referrer].add(quality); totalReferrerContrib = totalReferrerContrib.add(quality); } paidBoxes[_msgSender()] = paidBoxes[_msgSender()].add(quality); } function boxesAward(uint256 quality, address receiver) internal { uint256 salt = uint256(keccak256(abi.encodePacked(quality, receiver, totalSupply()))); uint256 seed = IRiverBoxRandom(randomGeneratorAddress).generateSignature(salt); for (uint256 i = 0; i < quality; ++i) { seed = seed.add(totalSupply()); uint256 randomIdx = uint256(keccak256(abi.encodePacked(seed))).mod(_stockLocations.length); (uint16 pawnLocationId, uint32 signature) = _pickLocation(randomIdx); Product memory newItem = Product(pawnLocationId, 0, signature, new uint256[](0)); uint256 newId = _awardItem(receiver); _tokenDetailsMapping[newId] = newItem; emit BoxAwarded(receiver, newId, block.timestamp); } } /** * @dev Fuse a list of items to a next level product */ function fuse(uint256[] memory tokenIds) external override whenNotPaused nonReentrant { _notContract(); require(!fuseLock, "fusing is locked"); require(verifyFusion(tokenIds), "not a valid list of tokens"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; Product memory newItem = Product(parentLocationId, 0, 0, tokenIds); for (uint256 i = 0; i < tokenIds.length; ++i) { _tokenDetailsMapping[tokenIds[i]].fusionCount = _tokenDetailsMapping[tokenIds[i]].fusionCount + 1; } uint256 newId = _awardItem(_msgSender()); _tokenDetailsMapping[newId] = newItem; emit FusedItemAwarded(_msgSender(), newId, block.timestamp); } /* ================ ADMIN ACTIONS ================ */ /** * @dev Set a new base URI * param newBaseURI new baseURI address */ function setBaseURI(string memory newBaseURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); baseURI = newBaseURI; } /** * @dev Set Hierarchy information to a specific node with locationId in batch * param locationIds A batch of locationId * param parentLocationIds A batch of parentLocationIds * param listChildLocationIds A batch of childLocationIds */ function setHierarchy( uint16[] memory locationIds, uint16[] memory parentLocationIds, uint16[][] memory listChildLocationIds ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint256 i = 0; i < locationIds.length; ++i) { _tokenHierarchyMapping[locationIds[i]] = Hierarchy(parentLocationIds[i], listChildLocationIds[i]); } } function batchSetPawnLocationStock(uint16[] memory locationIds, uint16[] memory locationIdStocks) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); for (uint16 locationIdx = 0; locationIdx < locationIds.length; ++locationIdx) { uint16 locationId = locationIds[locationIdx]; uint16 locationIdStock = locationIdStocks[locationIdx]; for (uint16 stockIdx = 0; stockIdx < locationIdStock; ++stockIdx) { _stockLocations.push(locationId); _stockCounter = _stockCounter + 1; require(_stockCounter >= 1, "SafeMath: addition overflow"); _stockSignatures.push(_stockCounter); } } } /** * @dev Triggers stopped state. */ function pause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _pause(); } /** * @dev Returns to normal state. */ function unPause() external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); _unpause(); } /** * @dev Triggers stopped state. * @param newPrice new box price */ function setBoxPrice(uint256 newPrice) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); boxPrice = newPrice; emit BoxPriceChanged(boxPrice, newPrice); } function setFuseLock(bool lock) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); fuseLock = lock; } /** * @dev Set random generator contract address * @param newAddress new random generator address */ function setRandomGenerator(address newAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); randomGeneratorAddress = newAddress; } function setTokenURI(uint256 tokenId, string memory _tokenURI) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); funderAddress = _funderAddress; devAddress = _devAddress; marketAddress = _marketAddress; devShare = _devShare; marketShare = _marketShare; } function withdraw(uint256 amount) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(address(this).balance >= amount, "amount exceeds balance"); uint256 devAmount = amount.mul(uint256(devShare)).div(100); uint256 marketAmount = amount.mul(uint256(marketShare)).div(100); payable(devAddress).transfer(devAmount); payable(marketAddress).transfer(marketAmount); payable(funderAddress).transfer(amount.sub(devAmount).sub(marketAmount)); } function batchAirDrop(address[] memory receivers, uint256[] memory qualities) external override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "require admin permission"); require(receivers.length == qualities.length, "receivers length must equal qualities length"); for (uint256 i = 0; i < qualities.length; ++i) { require(qualities[i] <= pawnsStock(), "out of stock"); totalClaimableAmount = totalClaimableAmount.add(qualities[i]); claimableAmountMapping[receivers[i]] = claimableAmountMapping[receivers[i]].add(qualities[i]); } } function claim(uint256 amount) external override whenNotPaused nonReentrant { _notContract(); require(amount <= claimableAmountMapping[_msgSender()], "out of claimable balance"); boxesAward(amount, _msgSender()); claimableAmountMapping[_msgSender()] = claimableAmountMapping[_msgSender()].sub(amount); totalClaimableAmount = totalClaimableAmount.sub(amount); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { //Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @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. */ library SafeMathUpgradeable { /** * @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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; interface IRiverBox { struct Hierarchy { uint16 parentLocationId; uint16[] childLocationIds; } struct Product { uint16 locationId; uint16 fusionCount; // number of times used to fuse item uint32 signature; // properties uint256[] parts; // a list token ids which are used to fuse this item } /* ================ EVENTS ================ */ /** * @dev Emitted when box price is changed. * @param from old price * @param to new price */ event BoxPriceChanged(uint256 indexed from, uint256 indexed to); event BoxAwarded(address indexed payer, uint256 indexed tokenId, uint256 eventTime); event FusedItemAwarded(address indexed payer, uint256 indexed tokenId, uint256 eventTime); /* ================ UTIL FUNCTIONS ================ */ /* ================ VIEWS ================ */ function tokenHierarchy(uint256 locationId) external view returns (Hierarchy memory); function tokenDetail(uint256 tokenId) external view returns (Product memory); function verifyFusion(uint256[] memory tokenIds) external view returns (bool); function tokenURI(uint256 tokenId) external view returns (string memory); function implementationVersion() external view returns (string memory); /* ================ TRANSACTIONS ================ */ function buy(uint256 quality, address referrer) external payable; function fuse(uint256[] memory tokenIds) external; /* ================ ADMIN ACTIONS ================ */ function setBaseURI(string memory newBaseURI) external; function setFuseLock(bool lock) external; function setHierarchy( uint16[] memory locationIds, uint16[] memory parentTokenIds, uint16[][] memory listChildTokenIds ) external; function pause() external; function unPause() external; function setBoxPrice(uint256 newPrice) external; function setRandomGenerator(address newAddress) external; function setTokenURI(uint256 tokenId, string memory _tokenURI) external; function setShare( address _funderAddress, address _devAddress, address _marketAddress, uint8 _devShare, uint8 _marketShare ) external; function withdraw(uint256 amount) external; function claim(uint256 amount) external; function batchAirDrop(address[] memory receivers, uint256[] memory qualitys) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma abicoder v2; interface IRiverBoxRandom { function generateSignature(uint256 salt) external view returns (uint256); function setCaller(address riverBox) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
Fuse a list of items to a next level product/
function fuse(uint256[] memory tokenIds) external override whenNotPaused nonReentrant { _notContract(); require(!fuseLock, "fusing is locked"); require(verifyFusion(tokenIds), "not a valid list of tokens"); uint16 parentLocationId = _tokenHierarchyMapping[_tokenDetailsMapping[tokenIds[0]].locationId].parentLocationId; Product memory newItem = Product(parentLocationId, 0, 0, tokenIds); for (uint256 i = 0; i < tokenIds.length; ++i) { _tokenDetailsMapping[tokenIds[i]].fusionCount = _tokenDetailsMapping[tokenIds[i]].fusionCount + 1; } uint256 newId = _awardItem(_msgSender()); _tokenDetailsMapping[newId] = newItem; emit FusedItemAwarded(_msgSender(), newId, block.timestamp); }
12,230,453
./full_match/5/0x08fA73274Dc7EF3Eb0CDBb5D6D07C8454cD48b5A/sources/_superfluid-finance/ethereum-contracts/contracts/interfaces/tokens/TokenInfo.sol
ERC20 token info interface Superfluid ERC20 standard interface does not specify these functions, but often the token implementations have them./
interface TokenInfo { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); pragma solidity >= 0.8.4; }
1,889,932
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Report Framework * @notice Smart Contract developed for the Harmony One Round 2 Hackathon on Gitcoin * @dev On-Chain reporting of a single metric and its count defined by a key and a category. * It will store each in a bucket denoted by the {Report}-{getReportingPeriodFor} function, * which defines a bucket given a timestamp. The report is configured for weekly reporting, * with a week starting on Sunday. Override the {getReportingPeriodFor} to derive your own reporting period. * * Note Use the provided API to update the global report or the latest reports. When updating the latest * reports, the global report is also updated. * Designed as real-time reporting. A global report keeps track of overall accumulated values. * * Note no overflow has been added ... something to be mindful of * * @author victaphu */ contract Report is Ownable { // a report period represents a single report period start/end date // a sum/count for each report period is provided when updating // reports hold all the keyed reports for a given date range struct ReportPeriod { uint256 startRange; uint256 endRange; uint256 sum; uint256 count; bytes[] keys; mapping(bytes => ReportOverview) reports; } // a report overview represents the next level and represents one level // further of details. the focus of the report is presented as a key struct ReportOverview { uint256 sum; uint256 count; bytes[] categories; mapping(bytes => ReportItem) reportItems; } // reports can be further divided into report items which represent the // lowest level of reporting. struct ReportItem { uint256 sum; uint256 count; } mapping(address => bool) private _access; uint256 constant DAY_IN_SECONDS = 86400; // this represents a global overview of reports ReportPeriod private _overallReport; mapping(uint256 => ReportPeriod) private reports; /** * @dev return the latest report object using the latest timestamp to find the * report from reports mapping. * * @return period latest report using timestamp to derive the timeslot */ function getLatestReportObject() internal view returns (ReportPeriod storage period) { period = reports[getLatestReportingPeriod()]; } /** * @dev given a unix timestamp (in seconds) return the current weekday * note week 0 is sunday, week 6 is saturday * * @param timestamp unix timestamp in seconds (e.g. block.timestamp) * @return weekday the day of week between 0 and 6 (inclusive) */ function getWeekday(uint256 timestamp) public pure returns (uint8 weekday) { weekday = uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } /** * @dev this function will take a timestamp and normalise it to a value. * By default, reports are normalised to closest start of the week, so this * function will help generate weekly reports * * @param timestamp is the UNIX timestamp (in seconds) e.g. the block.timestamp */ function getReportPeriodFor(uint256 timestamp) public view virtual returns (uint256 reportPeriod) { uint256 currentDOW = getWeekday(timestamp); timestamp = (timestamp - currentDOW * DAY_IN_SECONDS); timestamp = timestamp - timestamp % DAY_IN_SECONDS; reportPeriod = timestamp; } /** * @dev get the latest reporting period given the block timestamp. Return a normalised value * based on timestamp. By default we return normalised by week * * @return reportPeriod the normalised report period for the latest timestamp */ function getLatestReportingPeriod() public view returns (uint256 reportPeriod) { return getReportPeriodFor(block.timestamp); } /** * @dev grant access to selected reporter. only the owner of the report object may assign reporters * * @param reporter the address of user/contract that may update this report */ function grantAccess(address reporter) public onlyOwner { _access[reporter] = true; } /** * @dev revoke access for a selected reporter. only the owner of the report may revoke reporters * * @param reporter the address of the user/contract that we are revoking access */ function revokeAccess(address reporter) public onlyOwner { _access[reporter] = false; } modifier accessible() { require( _access[msg.sender] || owner() == msg.sender, "Cannot access reporting function" ); _; } /** * @dev update a report given the period and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1 * * @param period is the normalised period that we want to update. * @param value is the value to be added */ function updateReport(uint256 period, uint256 value) private { ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } latest.count += 1; latest.sum += value; } /** * @dev update a report given the period, key and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key represents one additional dimension of data recorded * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, uint256 value ) private { updateReport(period, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; if (overview.count == 0) { latest.keys.push(key); } overview.count += 1; overview.sum += value; } /** * @dev update a report given the period, key and category and the value. If the period is 0, then * the global report is updated. The sum is increased by the supplied value and the * count is incremented by 1. The key and category can be used to capture more fine-grain data * note data is rolled up to the parent * * @param period the normalised period that we want to update. * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateReport( uint256 period, bytes memory key, bytes memory category, uint256 value ) private { updateReport(period, key, value); ReportPeriod storage latest; if (period == 0) { latest = _overallReport; } else { latest = getLatestReportObject(); } ReportOverview storage overview = latest.reports[key]; ReportItem storage item = overview.reportItems[category]; if (item.count == 0) { overview.categories.push(category); overview.reportItems[category] = item; } item.count += 1; item.sum += value; } /** * @dev update the latest report, and update the global report for the running total * * @param value the value to be added */ function updateLatestReport(uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, value); updateReport(0, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param value the value to be added */ function updateLatestReport(bytes memory key, uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, value); updateReport(0, key, value); // update global report } /** * @dev update the latest report, and update the global report for the running total * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateLatestReport( bytes memory key, bytes memory category, uint256 value ) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, category, value); updateReport(0, key, category, value); // update global report } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param value the value to be added */ function updateGlobalReport(uint256 value) external accessible { updateReport(0, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param value the value to be added */ function updateGlobalReport(bytes memory key, uint256 value) external accessible { updateReport(0, key, value); } /** * @dev update the global report, this should be used if there is no intention to * have the report tool manage the running totals * * @param key the key dimension for this report * @param category the category dimension for this report * @param value the value to be added */ function updateGlobalReport( bytes memory key, bytes memory category, uint256 value ) external accessible { updateReport(0, key, category, value); } /** * @dev get the report for a given period. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } sum = report.sum; count = report.count; keys = report.keys; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = report.reports[keys[i]].sum; countStorage[i] = report.reports[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getReportForPeriod(uint256 period, bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportOverview storage reportOverview = report.reports[key]; sum = reportOverview.sum; count = reportOverview.count; keys = reportOverview.categories; uint256[] memory sumStorage = new uint256[](keys.length); uint256[] memory countStorage = new uint256[](keys.length); for (uint256 i = 0; i < keys.length; i++) { sumStorage[i] = reportOverview.reportItems[keys[i]].sum; countStorage[i] = reportOverview.reportItems[keys[i]].count; } sums = sumStorage; counts = countStorage; } /** * @dev get the report for a given period and key dimension. supply 0 for the argument to get the global report * note returns data for the next level, use the keys to query further * * @param period the period for which we want to retrieve the data * @param key the key dimension which we want to report on * @param category the category dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getReportForPeriod( uint256 period, bytes memory key, bytes memory category ) public view returns (uint256 sum, uint256 count) { ReportPeriod storage report; if (period == 0) { report = _overallReport; } else { report = reports[period]; } ReportItem storage item = report.reports[key].reportItems[category]; sum = item.sum; count = item.count; } /** * @dev get the latest report at the highest level. includes key dimension breakdown * note returns data for the next level, use the keys to query further * * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport() public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod()); } /** * @dev get the latest report for a key dimension * note returns data for the next level, use the categories to query further * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report * @return sums all the sums that have been accumulated so far * @return counts all the counts that have been accumulated so far * @return keys a list of key dimensions. sums, counts and keys have same length and indexed accordingly */ function getLatestReport(bytes memory key) public view returns ( uint256 sum, uint256 count, uint256[] memory sums, uint256[] memory counts, bytes[] memory keys ) { return getReportForPeriod(getLatestReportingPeriod(), key); } /** * @dev get the latest report for a key and category dimension * * @param key the key dimension which we want to report on * @return sum current accumulated sum * @return count current total count for the overall report */ function getLatestReport(bytes memory key, bytes memory category) public view returns (uint256 sum, uint256 count) { return getReportForPeriod(getLatestReportingPeriod(), key, category); } }
update the latest report, and update the global report for the running total key the key dimension for this report value the value to be added/
function updateLatestReport(bytes memory key, uint256 value) external accessible { uint256 period = getLatestReportingPeriod(); updateReport(period, key, value); }
12,965,576
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ // Sources flattened with hardhat v2.7.0 https://hardhat.org // File sol-temple/src/tokens/[email protected] pragma solidity >=0.8.0 <0.9.0; /* /* KEVIINNNNNNN /** * @title ERC721 * @notice A complete ERC721 implementation including metadata and enumerable * functions. Completely gas optimized and extensible. */ abstract contract ERC721 { /// @notice See {ERC721-Transfer}. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @notice See {ERC721-Approval}. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @notice See {ERC721-ApprovalForAll}. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. address[] private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < _owners.length, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(account_, i); } return ids; } /** * @notice Safely transfers `tokenId_` token from `from_` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. */ function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < _owners.length && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /** * @notice Same as {_safeMint}, but with an additional `data_` parameter which is * forwarded in {ERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners.push(to_); totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); delete _owners[tokenId_]; totalSupply--; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == 0x80ac58cd || // ERC721 interfaceId_ == 0x5b5e139f || // ERC721Metadata interfaceId_ == 0x780e9d63 || // ERC721Enumerable interfaceId_ == 0x01ffc9a7; // ERC165 } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) external returns (bytes4); } // File sol-temple/src/utils/[email protected] pragma solidity >=0.8.0 <0.9.0; /** * @title Auth * @notice Just a simple authing system. */ abstract contract Auth { /// @notice Emitted when the ownership is transfered. event OwnershipTransfered(address indexed from, address indexed to); /// @notice Contract's owner address. address public owner; /// @notice A simple modifier just to check whether the sender is the owner. modifier onlyOwner() { require(msg.sender == owner, "Auth: sender is not the owner"); _; } constructor() { _transferOwnership(msg.sender); } /// @notice Set the owner address to `owner_`. function transferOwnership(address owner_) public onlyOwner { require(owner != owner_, "Auth: transfering ownership to current owner"); _transferOwnership(owner_); } /// @notice Set the owner address to `owner_`. Does not require anything function _transferOwnership(address owner_) internal { address oldOwner = owner; owner = owner_; emit OwnershipTransfered(oldOwner, owner_); } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File contracts/KevinZuki.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract KevinZuki is Auth, ERC721 { using Strings for uint256; /// @notice Max supply. uint256 public constant SUPPLY_MAX = 1100; /// @notice Max amount per claim. uint256 public constant SUPPLY_PER_TX = 5; /// @notice 0 = CLOSED, 1 = PUBLIC, 2 = WHITELIST. uint256 public saleState; /// @notice OpenSea proxy registry. address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; /// @notice LooksRare marketplace transfer manager. address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e; /// @notice Check if marketplaces pre-approve is enabled. bool public marketplacesApproved = true; /// @notice Unrevelead URI. string public unrevealedURI; /// @notice Metadata base URI. string public baseURI; /// @notice Metadata base file extension. string public baseExtension; constructor(string memory newUnrevealedURI) ERC721("KevinZuki", "KevZuki") { unrevealedURI = newUnrevealedURI; } /// @notice Claim one or more tokens. function mint(uint256 amount) external payable { uint256 supply = totalSupply; require(supply + amount <= SUPPLY_MAX, "Max supply exceeded"); if (msg.sender != owner) { require(saleState == 1, "Public sale is not open"); require(amount > 0 && amount <= SUPPLY_PER_TX, "Invalid claim amount"); if (supply <= 333) require(msg.value == 0, "Invalid ether amount"); else require(msg.value == amount * 0.01 ether, "Invalid ether amount"); } for (uint256 i = 0; i < amount; i++) _safeMint(msg.sender, supply++); } /// @notice See {IERC721-tokenURI}. function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "ERC721Metadata: query for nonexisting token"); if (bytes(unrevealedURI).length > 0) return unrevealedURI; return string(abi.encodePacked(baseURI, id.toString(), baseExtension)); } /// @notice Set baseURI to `newBaseURI`. function setBaseURI(string memory newBaseURI, string memory newBaseExtension) external onlyOwner { baseURI = newBaseURI; baseExtension = newBaseExtension; delete unrevealedURI; } /// @notice Set unrevealedURI to `newUnrevealedURI`. function setUnrevealedURI(string memory newUnrevealedURI) external onlyOwner { unrevealedURI = newUnrevealedURI; } /// @notice Set saleState to `newSaleState`. function setSaleState(uint256 newSaleState) external onlyOwner { saleState = newSaleState; } /// @notice Set opensea to `newOpensea`. function setOpensea(address newOpensea) external onlyOwner { opensea = newOpensea; } /// @notice Set looksrare to `newLooksrare`. function setLooksrare(address newLooksrare) external onlyOwner { looksrare = newLooksrare; } /// @notice Toggle pre-approve feature state for sender. function toggleMarketplacesApproved() external onlyOwner { marketplacesApproved = !marketplacesApproved; } /// @notice Withdraw `value` of ether to the sender. function withdraw(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @notice Withdraw `value` of `token` to the sender. function withdrawERC20(IERC20 token, uint256 value) external onlyOwner { token.transfer(msg.sender, value); } /// @notice Withdraw `id` of `token` to the sender. function withdrawERC721(IERC721 token, uint256 id) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id); } /// @notice Withdraw `id` with `value` from `token` to the sender. function withdrawERC1155( IERC1155 token, uint256 id, uint256 value ) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id, value, ""); } /// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (!marketplacesApproved) return super.isApprovedForAll(owner, operator); return operator == address(ProxyRegistry(opensea).proxies(owner)) || operator == looksrare || super.isApprovedForAll(owner, operator); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
Set the owner address to `owner_`. Does not require anything
function _transferOwnership(address owner_) internal { address oldOwner = owner; owner = owner_; emit OwnershipTransfered(oldOwner, owner_); }
1,994,594
./partial_match/42/0xB875Cc93A183269A09E6667E1171b6dE6838B5b8/sources/tunaToken.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "tuna::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "tuna::delegateBySig: invalid nonce"); require(now <= expiry, "tuna::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
3,360,480
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../coffeeaccesscontrol/FarmerRole.sol"; import "../coffeeaccesscontrol/ConsumerRole.sol"; import "../coffeeaccesscontrol/RetailerRole.sol"; import "../coffeeaccesscontrol/DistributorRole.sol"; import "../coffeecore/SupplyChainToken.sol"; import "../../node_modules/@openzeppelin/contracts/access/Ownable.sol"; contract SupplyChain is Ownable, ConsumerRole, RetailerRole, DistributorRole, FarmerRole { // Define a variable called 'supplyChainToken' for self-defined ERC20 token SupplyChainToken supplyChainToken; // The value of supplyChainToken, tokenPrice = 1 means that 1 wei = 1 SCT uint256 tokenPrice; // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'items' that maps the UPC to an Item. mapping (uint => Item) items; // History structure, including current owner and its timestamp (block number) struct History{ address owner; uint timestamp; } // Define a public mapping 'itemsHistory' that maps the UPC to an array of History, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => History[8]) itemsHistory; // Define enum 'State' with the following values: enum State { Harvested, // 0 Processed, // 1 Packed, // 2 ForSale, // 3 Sold, // 4 Shipped, // 5 Received, // 6 Purchased // 7 } State constant defaultState = State.Harvested; // Define a struct 'Item' with the following fields: struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages address payable originFarmerID; // Metamask-Ethereum address of the Farmer string originFarmName; // Farmer Name string originFarmInformation; // Farmer Information string originFarmLatitude; // Farm Latitude string originFarmLongitude; // Farm Longitude uint productID; // Product ID potentially a combination of upc + sku string productNotes; // Product Notes uint productPrice; // Product Price State itemState; // Product State as represented in the enum above address payable distributorID; // Metamask-Ethereum address of the Distributor address retailerID; // Metamask-Ethereum address of the Retailer address payable consumerID; // Metamask-Ethereum address of the Consumer } // Define 8 events with the same 8 state values and accept 'upc' as input argument event Harvested(uint upc); event Processed(uint upc); event Packed(uint upc); event ForSale(uint upc); event Sold(uint upc); event Shipped(uint upc); event Received(uint upc); event Purchased(uint upc); //Define event for token purchased and sold event TokenPurchase(address indexed buyer, uint256 value); event TokenSell(address indexed buyer, uint256 value); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address, "This is not the required or expected address."); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price, "insufficient funds to cover the price of the item."); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; supplyChainToken.transfer(items[_upc].consumerID, amountToReturn); } modifier hasEnoughToken(uint _amount) { require(supplyChainToken.balanceOf(msg.sender) >= _amount, "insufficient funds"); _; } modifier hasEnoughAllowance(address spender, uint _amount) { require(supplyChainToken.allowance(address(this), msg.sender) >= _amount, "insufficient allowance"); _; } // Define a modifier that checks if an item.state of a upc is Harvested modifier harvested(uint _upc) { require(items[_upc].itemState == State.Harvested && items[_upc].sku != 0, "This is item is not currently in the state 'Harvested'"); _; } // Define a modifier that checks if an item.state of a upc is Processed modifier processed(uint _upc) { require(items[_upc].itemState == State.Processed, "This is item is not currently in the state 'Processed'"); _; } // Define a modifier that checks if an item.state of a upc is Packed modifier packed(uint _upc) { require(items[_upc].itemState == State.Packed, "This is item is not currently in the state 'Packed'"); _; } // Define a modifier that checks if an item.state of a upc is ForSale modifier forSale(uint _upc) { require(items[_upc].itemState == State.ForSale, "This is item is not currently in the state 'For Sale'"); _; } // Define a modifier that checks if an item.state of a upc is Sold modifier sold(uint _upc) { require(items[_upc].itemState == State.Sold, "This is item is not currently in the state 'Sold'"); _; } // Define a modifier that checks if an item.state of a upc is Shipped modifier shipped(uint _upc) { require(items[_upc].itemState == State.Shipped, "This is item is not currently in the state 'Shipped'"); _; } // Define a modifier that checks if an item.state of a upc is Received modifier received(uint _upc) { require(items[_upc].itemState == State.Received, "This is item is not currently in the state 'Received'"); _; } // Define a modifier that checks if an item.state of a upc is Purchased modifier purchased(uint _upc) { require(items[_upc].itemState == State.Purchased, "This is item is not currently in the state 'Purchased'"); _; } /** * @dev In the constructor set 'owner' to the address that instantiated the contract * and set 'sku' and 'upc' to 1 * @param _supplyChainTokenContract: the address of underlying supplyChainTokenContract * @param _tokenPrice: the price of supplyChainToken */ constructor(SupplyChainToken _supplyChainTokenContract, uint256 _tokenPrice) payable { transferOwnership(msg.sender); supplyChainToken = _supplyChainTokenContract; tokenPrice = _tokenPrice; sku = 1; upc = 1; } /** * @dev Users can buy tokens from this smart contract (the supplyChain contract) * @param _numberOfTokens: the amount that top-up to msg.sender * Emits an {TokenPurchase} event. */ function buyTokens(uint256 _numberOfTokens) public payable { require(msg.value >= _numberOfTokens * tokenPrice, 'Insufficient funds'); require(supplyChainToken.balanceOf(address(this)) >= _numberOfTokens, 'Out of liquility'); // increase tokens supplyChainToken.increaseAllowance(msg.sender, _numberOfTokens); emit TokenPurchase(msg.sender, _numberOfTokens); } /** * @dev Users can sell tokens to this smart contract (the supplyChain contract) * @param _numberOfTokens: the amount that decrease to msg.sender * Emits an {TokenSell} event. */ function sellTokens(uint256 _numberOfTokens) public hasEnoughToken(_numberOfTokens) { require(address(this).balance >= _numberOfTokens * tokenPrice, 'Out of liquility'); //decrease tokens supplyChainToken.decreaseAllowance(msg.sender, _numberOfTokens); //refund ether payable(msg.sender).transfer(_numberOfTokens * tokenPrice); emit TokenSell(msg.sender, _numberOfTokens); } /** * @dev Allows a farmer to mark an item 'Harvested', will self-increase sku * also marks farmer address and block number into itemHistory. Only a farmer can call it. * @param _upc: uint * @param _originFarmerID: address * @param _originFarmName: string * @param _originFarmInformation: string * @param _originFarmLatitude: string * @param _originFarmLongitude: string * @param _productNotes: string * Emits an {Harvested} event. */ function harvestItem(uint _upc, address payable _originFarmerID, string memory _originFarmName, string memory _originFarmInformation, string memory _originFarmLatitude, string memory _originFarmLongitude, string memory _productNotes) public onlyFarmer() { // Add the new item as part of Harvest items[_upc].sku = sku; items[_upc].upc = _upc; items[_upc].ownerID = _originFarmerID; items[_upc].originFarmerID = _originFarmerID; items[_upc].originFarmName = _originFarmName; items[_upc].originFarmInformation = _originFarmInformation; items[_upc].originFarmLatitude = _originFarmLatitude; items[_upc].originFarmLongitude = _originFarmLongitude; items[_upc].productNotes = _productNotes; items[_upc].itemState = State.Harvested; //itemsHistory? //History history = History(msg.sender, block.number); itemsHistory[_upc][0] = History(msg.sender, block.number); // Increment sku sku = sku + 1; // Emit the appropriate event emit Harvested(_upc); } /** * @dev Allows a farmer to mark an item 'Processed' * also marks farmer address and block number into itemHistory. Only a farmer can call it. * @param _upc: uint * Emits an {Processed} event. */ function processItem(uint _upc) public harvested(_upc) verifyCaller(msg.sender) onlyFarmer() { // Update the appropriate fields items[_upc].itemState = State.Processed; // Emit the appropriate event emit Processed(_upc); //itemsHistory? itemsHistory[_upc][1] = History(msg.sender, block.number); } /** * @dev Allows a farmer to mark an item 'Packed' * also marks farmer address and block number into itemHistory. Only a farmer can call it. * @param _upc: uint * Emits an {Packed} event. */ function packItem(uint _upc) public processed(_upc) verifyCaller(msg.sender) onlyFarmer() { // Update the appropriate fields items[_upc].itemState = State.Packed; // Emit the appropriate event emit Packed(_upc); //itemsHistory? itemsHistory[_upc][2] = History(msg.sender, block.number); } /** * @dev Allows a farmer to mark an item 'ForSale' * also marks farmer address and block number into itemHistory. Only a farmer can call it. * @param _upc: uint * Emits an {ForSale} event. */ function sellItem(uint _upc, uint _price) public packed(_upc) verifyCaller(msg.sender) onlyFarmer() { // Update the appropriate fields items[_upc].itemState = State.ForSale; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSale(_upc); //itemsHistory itemsHistory[_upc][3] = History(msg.sender, block.number); } function transferAllowance(address from, address to, uint amount) internal { supplyChainToken.decreaseAllowance(from, amount); supplyChainToken.increaseAllowance(to, amount); } /** * @dev Allows the disributor to mark an item 'Sold' * Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, * and any excess ether sent is refunded back to the buyer * also marks farmer address and block number into itemHistory. Only a Distributor can call it. * @param _upc: uint * Emits an {Sold} event. */ function buyItem(uint _upc) public payable forSale(_upc) hasEnoughAllowance(msg.sender, items[_upc].productPrice) onlyDistributor() { // Update the appropriate fields - ownerID, distributorID, itemState items[_upc].itemState = State.Sold; items[_upc].ownerID = payable(msg.sender); items[_upc].distributorID = payable(msg.sender); // Transfer money to farmer transferAllowance(msg.sender, items[_upc].originFarmerID, items[_upc].productPrice); // emit the appropriate event emit Sold(_upc); //itemsHistory itemsHistory[_upc][4] = History(msg.sender, block.number); } /** * @dev Allows the disributor to mark an item 'Shipped' * also marks farmer address and block number into itemHistory. Only a Farmer can call it. * @param _upc: uint * Emits an {Sold} event. */ function shipItem(uint _upc) public sold(_upc) verifyCaller(msg.sender) onlyFarmer() { // Update the appropriate fields items[_upc].itemState = State.Shipped; // emit the appropriate event emit Shipped(_upc); //itemsHistory itemsHistory[_upc][5] = History(msg.sender, block.number); } /** * @dev Allows the disributor to mark an item 'Received' * also marks farmer address and block number into itemHistory. Only a Retailer can call it. * @param _upc: uint * Emits an {Received} event. */ function receiveItem(uint _upc) public shipped(_upc) hasEnoughAllowance(msg.sender, items[_upc].productPrice) verifyCaller(msg.sender) onlyRetailer() // Access Control List enforced by calling Smart Contract / DApp //**** ^ not implemented so far { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].itemState = State.Received; items[_upc].ownerID = msg.sender; items[_upc].retailerID = msg.sender; // Pay to distributor transferAllowance(msg.sender, items[_upc].distributorID, items[_upc].productPrice); // Emit the appropriate event emit Received(_upc); itemsHistory[_upc][6] = History(msg.sender, block.number); } /** * @dev Allows the disributor to mark an item 'Purchased' * also marks farmer address and block number into itemHistory. Only a Retailer can call it. * @param _upc: uint * Emits an {Purchased} event. */ function purchaseItem(uint _upc) public received(_upc) verifyCaller(msg.sender) hasEnoughAllowance(msg.sender, items[_upc].productPrice) onlyConsumer() //no check to see if they paid? // Access Control List enforced by calling Smart Contract / DApp //**** ^ not implemented so far { // Update the appropriate fields - ownerID, consumerID, itemState items[_upc].itemState = State.Purchased; items[_upc].ownerID = msg.sender; items[_upc].consumerID = payable(msg.sender); // Pay to retailerID transferAllowance(msg.sender, items[_upc].retailerID, items[_upc].productPrice); // Emit the appropriate event emit Purchased(_upc); itemsHistory[_upc][7] = History(msg.sender, block.number); } function fetchItemHistory(uint _upc, uint index) public view returns(address owner, uint blockNumber) { require(index < 8, 'index out of bound'); owner = itemsHistory[_upc][index].owner; blockNumber = itemsHistory[_upc][index].timestamp; } /** * @dev Fetch item info of its producer. * @param _upc: uint * Returns (uint itemSKU, uint itemUPC, address ownerID, address farmerID, * string originFarmName, string originFarmInformation, string originFarmLatitude, * string originFarmLongitude) */ function fetchItemBufferOne(uint _upc) public view returns ( uint itemSKU, uint itemUPC, address ownerID, address originFarmerID, string memory originFarmName, string memory originFarmInformation, string memory originFarmLatitude, string memory originFarmLongitude ) { // Assign values to the 8 parameters itemSKU = items[_upc].sku; itemUPC = items[_upc].upc; //or just _upc; ownerID = items[_upc].ownerID; originFarmerID = items[_upc].originFarmerID; originFarmName = items[_upc].originFarmName; originFarmInformation = items[_upc].originFarmInformation; originFarmLatitude = items[_upc].originFarmLatitude; originFarmLongitude = items[_upc].originFarmLongitude; } /** * @dev Fetch item info of its producer. * @param _upc: uint * Returns (uint itemSKU, uint itemUPC, uint productID, string productNotes, * uint productPrice, State itemState, address distributorID, * address retailerID, address consumerID) */ function fetchItemBufferTwo(uint _upc) public view returns ( uint itemSKU, uint itemUPC, uint productID, string memory productNotes, uint productPrice, State itemState, address distributorID, address retailerID, address consumerID ) { // Assign values to the 9 parameters itemSKU = items[_upc].sku; itemUPC = items[_upc].upc; //or just _upc; productID = items[_upc].productID; productNotes = items[_upc].productNotes; productPrice = items[_upc].productPrice; itemState = items[_upc].itemState; distributorID = items[_upc].distributorID; retailerID = items[_upc].retailerID; consumerID = items[_upc].consumerID; } }
Allows the disributor to mark an item 'Shipped' also marks farmer address and block number into itemHistory. Only a Farmer can call it. _upc: uint Emits an {Sold} event./ Update the appropriate fields emit the appropriate eventitemsHistory
function shipItem(uint _upc) public sold(_upc) verifyCaller(msg.sender) onlyFarmer() { items[_upc].itemState = State.Shipped; emit Shipped(_upc); itemsHistory[_upc][5] = History(msg.sender, block.number); }
1,789,570
pragma solidity ^0.8.9; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./owner/Operator.sol"; contract ProfitDistribution is Operator { using SafeERC20 for IERC20; string public name = "ProfitDistribution"; // call it ProfitDistribution IERC20 public depositToken; address public burnAddress; uint256 public totalStaked; uint256 public depositFee; uint256 public totalBurned; uint256 public maxWithdrawFee; uint256 public feePeriod; //uint256[] public lockMultiplers; for later usage uint256 public totalAllocation; address[] public stakers; struct RewardInfo { IERC20 token; uint256 rewardsPerEpoch; uint256 totalRewards; bool isActive; uint256 distributedAmount; uint256 LastDistributedAmountPerAlloc; uint256[] rewardPerAllocHistory; } struct UserInfo { uint256 balance; uint256 allocation; bool hasStaked; bool isStaking; uint256 lastStakedTime; mapping(uint256=> uint256) lastSnapShotIndex; // Maps rewardPoolId to lastSnapshotindex mapping(uint256 => uint256) pendingRewards; // Maps rewardPoolId to amount } RewardInfo[] public rewardInfo; mapping(address => UserInfo) public userInfo; // in constructor pass in the address for reward token 1 and reward token 2 // that will be used to pay interest constructor(IERC20 _depositToken) { depositToken = _depositToken; burnAddress = 0x000000000000000000000000000000000000dEaD; //deposit fee default at 1% depositFee = 1000; //max withdraw fee default 7% maxWithdrawFee = 7000; feePeriod = 7 days; //totalBurned to 0 totalBurned = 0; } //Events event UpdateDepositFee(uint256 _depositFee); event UpdateMaxWithdrawFee(uint256 _Fee); event AddReward(IERC20 _token); event UpdateBurnAddress(address _burnAddress); event UpdateRewardsPerEpoch(uint256 _rewardId, uint256 _amount); event RewardIncrease(uint256 _rewardId, uint256 _amount); event RewardDecrease(uint256 _rewardId, uint256 _amount); event TotalStakedIncrease(uint256 _amount); event TotalStakedDecrease(uint256 _amount); event UserStakedIncrease(address _user, uint256 _amount); event UserStakedDecrease(address _user, uint256 _amount); event PendingRewardIncrease(address _user, uint256 _rewardId, uint256 _amount); event PendingRewardClaimed(address _user); event fees(address _user, uint256 fees); //update pending rewards modifier modifier updatePendingRewards(address _sender){ UserInfo storage user = userInfo[_sender]; for(uint256 i = 0; i < rewardInfo.length; ++i){ RewardInfo storage reward = rewardInfo[i]; //calculate pending rewards user.pendingRewards[i] = earned(_sender, i); user.lastSnapShotIndex[i] = reward.rewardPerAllocHistory.length -1; } _; } /*this function calculates the earnings of user over the last recorded epoch to the most recent epoch using average rewardPerAllocation over time*/ function earned(address _sender, uint256 _rewardId) public view returns (uint256) { UserInfo storage user = userInfo[_sender]; RewardInfo storage reward = rewardInfo[_rewardId]; uint256 latestRPA = reward.LastDistributedAmountPerAlloc; uint256 storedRPA = reward.rewardPerAllocHistory[user.lastSnapShotIndex[_rewardId]]; return user.allocation*(latestRPA - storedRPA)/(1e18)+ user.pendingRewards[_rewardId]; } //update deposit fee function updateDepositFee(uint256 _depositFee) external onlyOperator { require(_depositFee < 3000, "deposit fee too high"); depositFee = _depositFee; emit UpdateDepositFee(_depositFee); } function updateMaxWithdrawFee(uint256 _Fee) external onlyOperator { require(_Fee < 10000, "deposit fee too high"); maxWithdrawFee = _Fee; emit UpdateMaxWithdrawFee(_Fee); } function updateFeeTime(uint256 _time) external onlyOperator { require(_time < 30 days, "deposit fee too high"); feePeriod = _time* 1 hours; } //add more reward tokens function addReward(IERC20 _token) external onlyOperator { rewardInfo.push(RewardInfo({ token: _token, rewardsPerEpoch: 0, totalRewards: 0, isActive: false, distributedAmount:0, LastDistributedAmountPerAlloc:0, rewardPerAllocHistory: new uint256[](1) })); emit AddReward(_token); } // Update burn address function updateBurnAddress(address _burnAddress) external onlyOperator { burnAddress = _burnAddress; emit UpdateBurnAddress(_burnAddress); } // update the rewards per Epoch of each reward token function updateRewardsPerEpoch(uint256 _rewardId, uint256 _amount) external onlyOperator { RewardInfo storage reward = rewardInfo[_rewardId]; // checking amount require(_amount < reward.totalRewards,"amount must be lower than totalRewards"); // update rewards per epoch reward.rewardsPerEpoch = _amount; if (_amount == 0) { reward.isActive = false; } else { reward.isActive = true; } emit UpdateRewardsPerEpoch(_rewardId, _amount); } // supply rewards to contract function supplyRewards(uint256 _rewardId, uint256 _amount) external onlyOperator { RewardInfo storage reward = rewardInfo[_rewardId]; require(_amount > 0, "amount must be > 0"); // Update the rewards balance in map reward.totalRewards += _amount; emit RewardIncrease(_rewardId, _amount); // update status for tracking if (reward.totalRewards > 0 && reward.totalRewards > reward.rewardsPerEpoch) { reward.isActive = true; } // Transfer reward tokens to contract reward.token.safeTransferFrom(msg.sender, address(this), _amount); } //withdraw rewards out of contract function withdrawRewards(uint256 _rewardId, uint256 _amount) external onlyOperator { RewardInfo storage reward = rewardInfo[_rewardId]; require(_amount <= reward.totalRewards, "amount should be less than total rewards"); // Update the rewards balance in map reward.totalRewards -= _amount; emit RewardDecrease(_rewardId, _amount); // update status for tracking if (reward.totalRewards == 0 || reward.totalRewards < reward.rewardsPerEpoch) { reward.isActive = false; } // Transfer reward tokens out of contract reward.token.safeTransfer(msg.sender, _amount); } function stakeTokens(uint256 _amount) external updatePendingRewards(msg.sender){ address _sender = msg.sender; UserInfo storage user = userInfo[_sender]; require(_amount > 0, "can't stake 0"); user.lastStakedTime = block.timestamp; // 1% fee calculation uint256 feeAmount = _amount * depositFee / 100000; uint256 depositAmount = _amount - feeAmount; //update totalBurned totalBurned += feeAmount; // Update the staking balance in map user.balance += depositAmount; emit UserStakedIncrease(_sender, depositAmount); //update allocation user.allocation += depositAmount; totalAllocation += depositAmount; //update TotalStaked totalStaked += depositAmount; emit TotalStakedIncrease(depositAmount); // Add user to stakers array if they haven't staked already if(!user.hasStaked) { stakers.push(_sender); } // Update staking status to track user.isStaking = true; user.hasStaked = true; // Transfer based tokens to contract for staking depositToken.safeTransferFrom(_sender, address(this), _amount); // burn based depositToken.safeTransfer(burnAddress, feeAmount); } // allow user to unstake total balance and withdraw USDC from the contract function unstakeTokens(uint256 _amount) external updatePendingRewards(msg.sender) { address _sender = msg.sender; UserInfo storage user = userInfo[_sender]; require(_amount > 0, "can't unstake 0"); //check if amount is less than balance require(_amount <= user.balance, "staking balance too low"); //calculate fees uint current_fee = 0; if (feePeriod > (block.timestamp - user.lastStakedTime)){ current_fee = (feePeriod - (block.timestamp - user.lastStakedTime))*(1e18)/(feePeriod)*maxWithdrawFee/1e18; emit fees(msg.sender, current_fee); } uint256 feeAmount = _amount * current_fee / 100000; uint256 WithdrawAmount = _amount - feeAmount; //update user balance user.balance -= _amount; emit UserStakedDecrease(_sender, _amount); //update allocation user.allocation -= _amount; totalAllocation -= _amount; //update totalStaked totalStaked -= _amount; emit TotalStakedDecrease(_amount); // update the staking status if (user.balance == 0) { user.isStaking = false; } // transfer staked tokens out of this contract to the msg.sender depositToken.safeTransfer(_sender, WithdrawAmount); if (feeAmount > 0){ totalBurned += feeAmount; depositToken.safeTransfer(burnAddress, feeAmount); } } function issueInterestToken(uint256 _rewardId) public onlyOperator { RewardInfo storage reward = rewardInfo[_rewardId]; require(reward.isActive, "No rewards"); //update distributed amount and reward per allocations reward.distributedAmount += reward.rewardsPerEpoch; uint256 thisEpochRPA = reward.rewardsPerEpoch*(1e18)/totalAllocation; reward.LastDistributedAmountPerAlloc = reward.LastDistributedAmountPerAlloc + thisEpochRPA; reward.rewardPerAllocHistory.push(reward.LastDistributedAmountPerAlloc); if(reward.totalRewards > 0) { //update totalRewards reward.totalRewards -= reward.rewardsPerEpoch; emit RewardDecrease(_rewardId, reward.rewardsPerEpoch); } if (reward.totalRewards == 0 || reward.totalRewards < reward.rewardsPerEpoch) { reward.isActive = false; } } //get pending rewards function getPendingRewards(uint256 _rewardId, address _user) external view returns(uint256) { UserInfo storage user = userInfo[_user]; return user.pendingRewards[_rewardId]; } //get pending rewards function getLastSnapShotIndex(uint256 _rewardId, address _user) external view returns(uint256) { UserInfo storage user = userInfo[_user]; return user.lastSnapShotIndex[_rewardId]; } //collect rewards function collectRewards() external updatePendingRewards(msg.sender) { address _sender = msg.sender; UserInfo storage user = userInfo[_sender]; //update pendingRewards and collectRewards //loop through the reward IDs for(uint256 i = 0; i < rewardInfo.length; ++i){ //if pending rewards is not 0 if (user.pendingRewards[i] > 0){ RewardInfo storage reward = rewardInfo[i]; uint256 rewardsClaim = user.pendingRewards[i]; //reset pending rewards user.pendingRewards[i] = 0; //send rewards emit PendingRewardClaimed(_sender); reward.token.safeTransfer(_sender, rewardsClaim); } } } //get the pool share of a staker function getPoolShare(address _user) public view returns(uint256) { return (userInfo[_user].allocation * (1e18)) / totalStaked; } function distributeRewards() external onlyOperator { uint256 length = rewardInfo.length; for (uint256 i = 0; i < length; ++ i) { if (rewardInfo[i].isActive) { issueInterestToken(i); } } } }
get the pool share of a staker
function getPoolShare(address _user) public view returns(uint256) { return (userInfo[_user].allocation * (1e18)) / totalStaked; }
12,854,325
// // FormSI060719, which is part of the show "Garage Politburo" at Susan Inglett Gallery, NY. // June 7, 2019 - July 26, 2019 // For more information see https://github.com/GaragePolitburo/FormSI060719 // Based on code by OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC721 // Used Jan 4 2019 Open Zepplin package 76abd1a41ec7d96ef76370f3eadfe097226896a2 // Based also on CryptoPunks by Larva Labs: // https://github.com/larvalabs/cryptopunks // Text snippets taken from Fredric Jameson, Masha Gessen, Nisi Shawl, Margaret Thatcher, // Leni Zumas, Philip Roth, Omar El Akkad, Wayne La Pierre, David Graeber, // Walt Whitman, George Orwell, Rudyard Kipling, and Donna Haraway. pragma solidity ^0.5.0; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract FormSI060719 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ // FORM string private _name = "FormSI060719 :: Garage Politburo Tokens"; string private _symbol = "SIGP"; string[] private _theFormSI060719; uint256[2][] private _theIndexToQA; //tokeId gives (questionId, textId) uint256[][13] private _theQAtoIndex; // [questionId, textid] gives tokenId uint256 private _totalSupply; uint256[13] private _supplyPerQ; uint256 public numberOfQuestions = 13; string[] private _qSection; string private _qForm; // END FORM //AUCTION // Put list element up for sale by owner. Can be linked to specific // potential buyer struct forSaleInfo { bool isForSale; uint256 tokenId; address seller; uint256 minValue; //in wei.... everything in wei address onlySellTo; // specify to sell only to a specific person } // Place bid for specific list element struct bidInfo { bool hasBid; uint256 tokenId; address bidder; uint256 value; } // Public info about tokens for sale. mapping (uint256 => forSaleInfo) public marketForSaleInfoByIndex; // Public info about highest bid for each token. mapping (uint256 => bidInfo) public marketBidInfoByIndex; // Information about withdrawals (in units of wei) available // ... for addresses due to failed bids, successful sales, etc... mapping (address => uint256) public marketPendingWithdrawals; //END AUCTION //EVENTS // In addition to Transfer, Approval, and ApprovalForAll IERC721 events event QuestionAnswered(uint256 indexed questionId, uint256 indexed answerId, address indexed by); event ForSaleDeclared(uint256 indexed tokenId, address indexed from, uint256 minValue,address indexed to); event ForSaleWithdrawn(uint256 indexed tokenId, address indexed from); event ForSaleBought(uint256 indexed tokenId, uint256 value, address indexed from, address indexed to); event BidDeclared(uint256 indexed tokenId, uint256 value, address indexed from); event BidWithdrawn(uint256 indexed tokenId, uint256 value, address indexed from); event BidAccepted(uint256 indexed tokenId, uint256 value, address indexed from, address indexed to); //END EVENTS constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _qForm = "FormSI060719 :: freeAssociationAndResponse :: "; _qSection.push("Section 0-2b :: "); _qSection.push("Section2-TINA :: "); _qSection.push("Section2b-WS :: "); _theFormSI060719.push("When we ask ourselves \"How are we?\" :: we really want to know ::"); _theQAtoIndex[0].push(0); _theIndexToQA.push([0,0]); _tokenOwner[0] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[0] = 1; _theFormSI060719.push("How are we to ensure equitable merit-based access? :: Tried to cut down :: used more than intended :: "); _theQAtoIndex[1].push(1); _theIndexToQA.push([1,0]); _tokenOwner[1] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[1] = 1; _theFormSI060719.push("Psychoanalytic Placement Bureau ::"); _theQAtoIndex[2].push(2); _theIndexToQA.push([2,0]); _tokenOwner[2] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[2] = 1; _theFormSI060719.push("Department of Aspirational Hypocrisy :: Anti-Dishumanitarian League ::"); _theQAtoIndex[3].push(3); _theIndexToQA.push([3,0]); _tokenOwner[3] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[3] = 1; _theFormSI060719.push("Personhood Amendment :: Homestead 42 ::"); _theQAtoIndex[4].push(4); _theIndexToQA.push([4,0]); _tokenOwner[4] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[4] = 1; _theFormSI060719.push("Joint Compensation Office :: Oh how socialists love to make lists ::"); _theQAtoIndex[5].push(5); _theIndexToQA.push([5,0]); _tokenOwner[5] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[5] = 1; _theFormSI060719.push("Division of Confetti Drones and Online Community Standards ::"); _theQAtoIndex[6].push(6); _theIndexToQA.push([6,0]); _tokenOwner[6] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[6] = 1; _theFormSI060719.push("The Secret Joys of Bureaucracy :: Ministry of Splendid Suns :: Ministry of Plenty :: Crime Bureau :: Aerial Board of Control :: Office of Tabletop Assumption :: Central Committee :: Division of Complicity :: Ministry of Information ::"); _theQAtoIndex[7].push(7); _theIndexToQA.push([7,0]); _tokenOwner[7] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[7] = 1; _theFormSI060719.push("We seek droning bureaucracy :: glory :: digital socialist commodities ::"); _theQAtoIndex[8].push(8); _theIndexToQA.push([8,0]); _tokenOwner[8] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[8] = 1; _theFormSI060719.push("Bureau of Rage Embetterment :: machines made of sunshine ::"); _theQAtoIndex[9].push(9); _theIndexToQA.push([9,0]); _tokenOwner[9] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[9] = 1; _theFormSI060719.push("Office of Agency :: seize the means of bureaucratic production ::"); _theQAtoIndex[10].push(10); _theIndexToQA.push([10,0]); _tokenOwner[10] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[10] = 1; _theFormSI060719.push("Garage Politburo :: Boutique Ministry ::"); _theQAtoIndex[11].push(11); _theIndexToQA.push([11,0]); _tokenOwner[11] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[11] = 1; _theFormSI060719.push("Grassroots :: Tabletop :: Bureaucracy Saves! ::"); _theQAtoIndex[12].push(12); _theIndexToQA.push([12,0]); _tokenOwner[12] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); _supplyPerQ[12] = 1; _totalSupply = 13; assert (_totalSupply == numberOfQuestions); assert (_totalSupply == _ownedTokensCount[msg.sender]); } //Begin Form function name() external view returns (string memory){ return _name; } function totalSupply() external view returns (uint256){ return _totalSupply; } function symbol() external view returns (string memory){ return _symbol; } // questionId goes from 0 to numberOfQuestions - 1 function getFormQuestion(uint256 questionId) public view returns (string memory){ return (_getQAtext(questionId, 0)); } // questionId goes from 0 to numberOfQuestions - 1 // answerId goes from 1 to _supplyPerQ - 1 // If there are no answers to questionId, this function reverts function getFormAnswers(uint256 questionId, uint256 answerId) public view returns (string memory){ require (answerId > 0); return (_getQAtext(questionId, answerId)); } function _getQAtext(uint256 questionId, uint256 textId) private view returns (string memory){ require (questionId < numberOfQuestions); require (textId < _supplyPerQ[questionId]); if (textId > 0){ return (_theFormSI060719[_theQAtoIndex[questionId][textId]]); } else { bytes memory qPrefix; if (questionId <= 1) { qPrefix = bytes(_qSection[0]); } if ((questionId >= 2) && (questionId <= 6)){ qPrefix = bytes(_qSection[1]); } if (questionId >= 7){ qPrefix = bytes(_qSection[2]); } return (string(abi.encodePacked(bytes(_qForm), qPrefix, bytes(_theFormSI060719[_theQAtoIndex[questionId][textId]])))); } } function answerQuestion(uint256 questionId, string calldata answer) external returns (bool){ require (questionId < numberOfQuestions); require (bytes(answer).length != 0); _theFormSI060719.push(answer); _totalSupply = _totalSupply.add(1); _supplyPerQ[questionId] = _supplyPerQ[questionId].add(1); _theQAtoIndex[questionId].push(_totalSupply - 1); _theIndexToQA.push([questionId, _supplyPerQ[questionId] - 1]); _tokenOwner[_totalSupply - 1] = msg.sender; _ownedTokensCount[msg.sender] = _ownedTokensCount[msg.sender].add(1); emit QuestionAnswered(questionId, _supplyPerQ[questionId] - 1, msg.sender); return true; } // Returns index of ERC721 token // questionId start with index 0 // textId 0 returns the question text associated with questionId // textId 1 returns the first answer to questionId, etc... function getIndexfromQA(uint256 questionId, uint256 textId) public view returns (uint256) { require (questionId < numberOfQuestions); require (textId < _supplyPerQ[questionId]); return _theQAtoIndex[questionId][textId]; } // Returns (questionId, textId) // questionId starts with index 0 // textId starts with index 0 // textId = 0 corresponds to question text // textId > 0 corresponts to answers function getQAfromIndex(uint256 tokenId) public view returns (uint256[2] memory) { require (tokenId < _totalSupply); return ([_theIndexToQA[tokenId][0] ,_theIndexToQA[tokenId][1]]) ; } function getNumberOfAnswers(uint256 questionId) public view returns (uint256){ require (questionId < numberOfQuestions); return (_supplyPerQ[questionId] - 1); } //End Form /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { // this checks if token exists require(_isApprovedOrOwner(msg.sender, tokenId)); // remove for sale, if it exists. if (marketForSaleInfoByIndex[tokenId].isForSale){ marketForSaleInfoByIndex[tokenId] = forSaleInfo(false, tokenId, address(0), 0, address(0)); emit ForSaleWithdrawn(tokenId, _tokenOwner[tokenId]); } _transferFrom(from, to, tokenId); // remove bid of recipient (and now new owner), if it exists. // Need to do this since marketWithdrawBid requires that msg.sender not owner. if (marketBidInfoByIndex[tokenId].bidder == to){ _clearNewOwnerBid(to, tokenId); } } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _ownedTokensCount[to] = _ownedTokensCount[to].add(1); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } //MARKET // Let anyone interested know that the owner put a token up for sale. // Anyone can obtain it by sending an amount of wei equal to or // larger than _minPriceInWei. // Only token owner can use this function. function marketDeclareForSale(uint256 tokenId, uint256 minPriceInWei) external returns (bool){ require (_exists(tokenId)); require (msg.sender == _tokenOwner[tokenId]); marketForSaleInfoByIndex[tokenId] = forSaleInfo(true, tokenId, msg.sender, minPriceInWei, address(0)); emit ForSaleDeclared(tokenId, msg.sender, minPriceInWei, address(0)); return true; } // Let anyone interested know that the owner put a token up for sale. // Only the address _to can obtain it by sending an amount of wei equal // to or larger than _minPriceInWei. // Only token owner can use this function. function marketDeclareForSaleToAddress(uint256 tokenId, uint256 minPriceInWei, address to) external returns(bool){ require (_exists(tokenId)); require (msg.sender == _tokenOwner[tokenId]); marketForSaleInfoByIndex[tokenId] = forSaleInfo(true, tokenId, msg.sender, minPriceInWei, to); emit ForSaleDeclared(tokenId, msg.sender, minPriceInWei, to); return true; } // Owner no longer wants token for sale, or token has changed owner, // so previously posted for sale is no longer valid. // Only token owner can use this function. function marketWithdrawForSale(uint256 tokenId) public returns(bool){ require (_exists(tokenId)); require(msg.sender == _tokenOwner[tokenId]); marketForSaleInfoByIndex[tokenId] = forSaleInfo(false, tokenId, address(0), 0, address(0)); emit ForSaleWithdrawn(tokenId, msg.sender); return true; } // I'll take it. Must send at least as many wei as minValue in // forSale structure. function marketBuyForSale(uint256 tokenId) payable external returns(bool){ require (_exists(tokenId)); forSaleInfo storage existingForSale = marketForSaleInfoByIndex[tokenId]; require(existingForSale.isForSale); require(existingForSale.onlySellTo == address(0) || existingForSale.onlySellTo == msg.sender); require(msg.value >= existingForSale.minValue); address seller = _tokenOwner[tokenId]; require(existingForSale.seller == seller); _transferFrom(seller, msg.sender, tokenId); // must withdrawal for sale after transfer to make sure msg.sender // is the current owner. marketWithdrawForSale(tokenId); // clear bid of new owner, if it exists. if (marketBidInfoByIndex[tokenId].bidder == msg.sender){ _clearNewOwnerBid(msg.sender, tokenId); } marketPendingWithdrawals[seller] = marketPendingWithdrawals[seller].add(msg.value); emit ForSaleBought(tokenId, msg.value, seller, msg.sender); return true; } // Potential buyer puts up money for a token. function marketDeclareBid(uint256 tokenId) payable external returns(bool){ require (_exists(tokenId)); require (_tokenOwner[tokenId] != msg.sender); require (msg.value > 0); bidInfo storage existingBid = marketBidInfoByIndex[tokenId]; // Keep only the highest bid. require (msg.value > existingBid.value); if (existingBid.value > 0){ marketPendingWithdrawals[existingBid.bidder] = marketPendingWithdrawals[existingBid.bidder].add(existingBid.value); } marketBidInfoByIndex[tokenId] = bidInfo(true, tokenId, msg.sender, msg.value); emit BidDeclared(tokenId, msg.value, msg.sender); return true; } // Potential buyer changes mind and withdrawals bid. function marketWithdrawBid(uint256 tokenId) external returns(bool){ require (_exists(tokenId)); require (_tokenOwner[tokenId] != msg.sender); bidInfo storage existingBid = marketBidInfoByIndex[tokenId]; require (existingBid.hasBid); require (existingBid.bidder == msg.sender); uint256 amount = existingBid.value; // Refund marketPendingWithdrawals[existingBid.bidder] = marketPendingWithdrawals[existingBid.bidder].add(amount); marketBidInfoByIndex[tokenId] = bidInfo(false, tokenId, address(0), 0); emit BidWithdrawn(tokenId, amount, msg.sender); return true; } // Owner accepts bid, and money and token change hands. All money in wei. // Only token owner can use this function. function marketAcceptBid(uint256 tokenId, uint256 minPrice) external returns(bool){ require (_exists(tokenId)); address seller = _tokenOwner[tokenId]; require (seller == msg.sender); bidInfo storage existingBid = marketBidInfoByIndex[tokenId]; require (existingBid.hasBid); require (existingBid.value >= minPrice); address buyer = existingBid.bidder; // Remove for sale while msg.sender still owner or approved. marketWithdrawForSale(tokenId); _transferFrom (seller, buyer, tokenId); uint256 amount = existingBid.value; // Remove bid. marketBidInfoByIndex[tokenId] = bidInfo(false, tokenId, address(0),0); marketPendingWithdrawals[seller] = marketPendingWithdrawals[seller].add(amount); emit BidAccepted(tokenId, amount, seller, buyer); return true; } // Retrieve money to successful sale, failed bid, withdrawn bid, etc. // All in wei. Note that refunds, income, etc. are NOT automatically // deposited in the user's address. The user must withdraw the funds. function marketWithdrawWei() external returns(bool) { uint256 amount = marketPendingWithdrawals[msg.sender]; require (amount > 0); marketPendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); return true; } // Clears bid when become owner changes via forSaleBuy or transferFrom. function _clearNewOwnerBid(address to, uint256 tokenId) internal { uint256 amount = marketBidInfoByIndex[tokenId].value; marketBidInfoByIndex[tokenId] = bidInfo(false, tokenId, address(0), 0); marketPendingWithdrawals[to] = marketPendingWithdrawals[to].add(amount); emit BidWithdrawn(tokenId, amount, to); } //END MARKET }
Transfers the ownership of a given token ID to another address Usage of this method is discouraged, use `safeTransferFrom` whenever possible Requires the msg sender to be the owner, approved, or operator from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred/ this checks if token exists remove for sale, if it exists. remove bid of recipient (and now new owner), if it exists. Need to do this since marketWithdrawBid requires that msg.sender not owner.
function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); if (marketForSaleInfoByIndex[tokenId].isForSale){ marketForSaleInfoByIndex[tokenId] = forSaleInfo(false, tokenId, address(0), 0, address(0)); emit ForSaleWithdrawn(tokenId, _tokenOwner[tokenId]); } _transferFrom(from, to, tokenId); if (marketBidInfoByIndex[tokenId].bidder == to){ _clearNewOwnerBid(to, tokenId); } }
891,584
./partial_match/1/0x6b9e434b3e164EBc88c1f3cfAB8361C2d00a016e/sources/CTPurchaseOffer.sol
Allows withdrawal of purchase offer contract by the buyer. Can only be called by the buyer or the seller/
function withdrawOffer() external { require(offer.buyer == msg.sender || offer.seller == msg.sender); require(offer.active); tokenController.transfer(offer.buyer, offer.gtAmount); offer.active = false; emit WithdrawPurchaseOffer(address(this)); }
16,039,171
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IKeeperSubsidyPool.sol"; import "./interfaces/IUniswapRouterV2.sol"; import "./interfaces/IUniswapFactory.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IEToken.sol"; import "./interfaces/IEPoolPeriphery.sol"; import "./interfaces/IEPool.sol"; import "./utils/ControllerMixin.sol"; import "./utils/TokenUtils.sol"; import "./EPoolLibrary.sol"; import "hardhat/console.sol"; contract EPoolPeriphery is ControllerMixin, IEPoolPeriphery { using SafeERC20 for IERC20; using TokenUtils for IERC20; using TokenUtils for IEToken; IUniswapV2Factory public immutable override factory; IUniswapV2Router01 public immutable override router; // Keeper subsidy pool for making rebalancing via flash swaps capital neutral for msg.sender IKeeperSubsidyPool public immutable override keeperSubsidyPool; // supported EPools by the periphery mapping(address => bool) public override ePools; // max. allowed slippage between EPool oracle and uniswap when executing a flash swap uint256 public override maxFlashSwapSlippage; event IssuedEToken( address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user ); event RedeemedEToken( address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user ); event SetEPoolApproval(address indexed ePool, bool approval); event SetMaxFlashSwapSlippage(uint256 maxFlashSwapSlippage); event RecoveredToken(address token, uint256 amount); /** * @param _controller Address of the controller * @param _factory Address of the Uniswap V2 factory * @param _router Address of the Uniswap V2 router * @param _keeperSubsidyPool Address of keeper subsidiy pool * @param _maxFlashSwapSlippage Max. allowed slippage between EPool oracle and uniswap */ constructor( IController _controller, IUniswapV2Factory _factory, IUniswapV2Router01 _router, IKeeperSubsidyPool _keeperSubsidyPool, uint256 _maxFlashSwapSlippage ) ControllerMixin(_controller) { factory = _factory; router = _router; keeperSubsidyPool = _keeperSubsidyPool; maxFlashSwapSlippage = _maxFlashSwapSlippage; // e.g. 1.05e18 -> 5% slippage } /** * @notice Returns the address of the current Aggregator which provides the exchange rate between TokenA and TokenB * @return Address of aggregator */ function getController() external view override returns (address) { return address(controller); } /** * @notice Updates the Controller * @dev Can only called by an authorized sender * @param _controller Address of the new Controller * @return True on success */ function setController(address _controller) external override onlyDao("EPoolPeriphery: not dao") returns (bool) { _setController(_controller); return true; } /** * @notice Give or revoke approval a EPool for the EPoolPeriphery * @dev Can only called by the DAO or the guardian * @param ePool Address of the EPool * @param approval Boolean on whether approval for EPool should be given or revoked * @return True on success */ function setEPoolApproval( IEPool ePool, bool approval ) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) { if (approval) { // assuming EPoolPeriphery only holds funds within calls ePool.tokenA().approve(address(ePool), type(uint256).max); ePool.tokenB().approve(address(ePool), type(uint256).max); ePools[address(ePool)] = true; } else { ePool.tokenA().approve(address(ePool), 0); ePool.tokenB().approve(address(ePool), 0); ePools[address(ePool)] = false; } emit SetEPoolApproval(address(ePool), approval); return true; } /** * @notice Set max. slippage between EPool oracle and uniswap when performing flash swap * @dev Can only be callede by the DAO or the guardian * @param _maxFlashSwapSlippage Max. flash swap slippage * @return True on success */ function setMaxFlashSwapSlippage( uint256 _maxFlashSwapSlippage ) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) { maxFlashSwapSlippage = _maxFlashSwapSlippage; emit SetMaxFlashSwapSlippage(maxFlashSwapSlippage); return true; } /** * @notice Issues an amount of EToken for maximum amount of TokenA * @dev Reverts if maxInputAmountA is exceeded. Unused amount of TokenA is refunded to msg.sender. * Requires setting allowance for TokenA. * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to issue * @param maxInputAmountA Max. amount of TokenA to deposit * @param deadline Timestamp at which tx expires * @return True on success */ function issueForMaxTokenA( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountA, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); tokenA.safeTransferFrom(msg.sender, address(this), maxInputAmountA); IEPool.Tranche memory t = ePool.getTranche(eToken); (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); // swap part of input amount for amountB require(maxInputAmountA >= amountA, "EPoolPeriphery: insufficient max. input"); uint256 amountAToSwap = maxInputAmountA - amountA; address[] memory path = new address[](2); path[0] = address(tokenA); path[1] = address(tokenB); tokenA.approve(address(router), amountAToSwap); uint256[] memory amountsOut = router.swapTokensForExactTokens( amountB, amountAToSwap, path, address(this), deadline ); // do the deposit (TokenA is already approved) ePool.issueExact(eToken, amount); // transfer EToken to msg.sender IERC20(eToken).safeTransfer(msg.sender, amount); // refund unused maxInputAmountA -= amountA + amountASwappedForAmountB tokenA.safeTransfer(msg.sender, maxInputAmountA - amountA - amountsOut[0]); emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Issues an amount of EToken for maximum amount of TokenB * @dev Reverts if maxInputAmountB is exceeded. Unused amount of TokenB is refunded to msg.sender. * Requires setting allowance for TokenB. * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to issue * @param maxInputAmountB Max. amount of TokenB to deposit * @param deadline Timestamp at which tx expires * @return True on success */ function issueForMaxTokenB( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountB, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); tokenB.safeTransferFrom(msg.sender, address(this), maxInputAmountB); IEPool.Tranche memory t = ePool.getTranche(eToken); (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); // swap part of input amount for amountB require(maxInputAmountB >= amountB, "EPoolPeriphery: insufficient max. input"); uint256 amountBToSwap = maxInputAmountB - amountB; address[] memory path = new address[](2); path[0] = address(tokenB); path[1] = address(tokenA); tokenB.approve(address(router), amountBToSwap); uint256[] memory amountsOut = router.swapTokensForExactTokens( amountA, amountBToSwap, path, address(this), deadline ); // do the deposit (TokenB is already approved) ePool.issueExact(eToken, amount); // transfer EToken to msg.sender IERC20(eToken).safeTransfer(msg.sender, amount); // refund unused maxInputAmountB -= amountB + amountBSwappedForAmountA tokenB.safeTransfer(msg.sender, maxInputAmountB - amountB - amountsOut[0]); emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Redeems an amount of EToken for a min. amount of TokenA * @dev Reverts if minOutputA is not met. Requires setting allowance for EToken * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to redeem * @param minOutputA Min. amount of TokenA to withdraw * @param deadline Timestamp at which tx expires * @return True on success */ function redeemForMinTokenA( IEPool ePool, address eToken, uint256 amount, uint256 minOutputA, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount); // do the withdraw IERC20(eToken).approve(address(ePool), amount); (uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount); // convert amountB withdrawn from EPool into TokenA address[] memory path = new address[](2); path[0] = address(tokenB); path[1] = address(tokenA); tokenB.approve(address(router), amountB); uint256[] memory amountsOut = router.swapExactTokensForTokens( amountB, 0, path, address(this), deadline ); uint256 outputA = amountA + amountsOut[1]; require(outputA >= minOutputA, "EPoolPeriphery: insufficient output amount"); IERC20(tokenA).safeTransfer(msg.sender, outputA); emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Redeems an amount of EToken for a min. amount of TokenB * @dev Reverts if minOutputB is not met. Requires setting allowance for EToken * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to redeem * @param minOutputB Min. amount of TokenB to withdraw * @param deadline Timestamp at which tx expires * @return True on success */ function redeemForMinTokenB( IEPool ePool, address eToken, uint256 amount, uint256 minOutputB, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount); // do the withdraw IERC20(eToken).approve(address(ePool), amount); (uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount); // convert amountB withdrawn from EPool into TokenA address[] memory path = new address[](2); path[0] = address(tokenA); path[1] = address(tokenB); tokenA.approve(address(router), amountA); uint256[] memory amountsOut = router.swapExactTokensForTokens( amountA, 0, path, address(this), deadline ); uint256 outputB = amountB + amountsOut[1]; require(outputB >= minOutputB, "EPoolPeriphery: insufficient output amount"); IERC20(tokenB).safeTransfer(msg.sender, outputB); emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Rebalances a EPool. Capital required for rebalancing is obtained via a flash swap. * The potential slippage between the EPool oracle and uniswap is covered by the KeeperSubsidyPool. * @dev Fails if maxFlashSwapSlippage is exceeded in uniswapV2Call * @param ePool Address of the EPool to rebalance * @param fracDelta Fraction of the delta to rebalance (1e18 for rebalancing the entire delta) * @return True on success */ function rebalanceWithFlashSwap( IEPool ePool, uint256 fracDelta ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (address tokenA, address tokenB) = (address(ePool.tokenA()), address(ePool.tokenB())); (uint256 deltaA, uint256 deltaB, uint256 rChange, ) = EPoolLibrary.delta( ePool.getTranches(), ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(address(tokenA), address(tokenB))); // map deltaA, deltaB to amountOut0, amountOut1 uint256 amountOut0; uint256 amountOut1; if (rChange == 0) { (amountOut0, amountOut1) = (address(tokenA) == pair.token0()) ? (uint256(0), deltaB) : (deltaB, uint256(0)); } else { (amountOut0, amountOut1) = (address(tokenA) == pair.token0()) ? (deltaA, uint256(0)) : (uint256(0), deltaA); } bytes memory data = abi.encode(ePool, fracDelta); pair.swap(amountOut0, amountOut1, address(this), data); return true; } /** * @notice rebalanceAllWithFlashSwap callback called by the uniswap pair * @dev Trusts that deltas are actually forwarded by the EPool. * Verifies that funds are forwarded from flash swap of the uniswap pair. * param sender Address of the flash swap initiator * param amount0 * param amount1 * @param data Data forwarded in the flash swap */ function uniswapV2Call( address /* sender */, // skip sender check, check for forwarded funds by flash swap is sufficient uint256 /* amount0 */, uint256 /* amount1 */, bytes calldata data ) external { (IEPool ePool, uint256 fracDelta) = abi.decode(data, (IEPool, uint256)); require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); // fails if no funds are forwarded in the flash swap callback from the uniswap pair // TokenA, TokenB are already approved (uint256 deltaA, uint256 deltaB, uint256 rChange, ) = ePool.rebalance(fracDelta); address[] memory path = new address[](2); // [0] flash swap repay token, [1] flash lent token uint256 amountsIn; // flash swap repay amount uint256 deltaOut; if (rChange == 0) { // release TokenA, add TokenB to EPool -> flash swap TokenB, repay with TokenA path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); (amountsIn, deltaOut) = (router.getAmountsIn(deltaB, path)[0], deltaA); } else { // add TokenA, release TokenB to EPool -> flash swap TokenA, repay with TokenB path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); (amountsIn, deltaOut) = (router.getAmountsIn(deltaA, path)[0], deltaB); } // if slippage is negative request subsidy, if positive top of KeeperSubsidyPool if (amountsIn > deltaOut) { require( amountsIn * EPoolLibrary.sFactorI / deltaOut <= maxFlashSwapSlippage, "EPoolPeriphery: excessive slippage" ); keeperSubsidyPool.requestSubsidy(path[0], amountsIn - deltaOut); } else if (amountsIn < deltaOut) { IERC20(path[0]).safeTransfer(address(keeperSubsidyPool), deltaOut - amountsIn); } // repay flash swap by sending amountIn to pair IERC20(path[0]).safeTransfer(msg.sender, amountsIn); } /** * @notice Recovers untracked amounts * @dev Can only called by an authorized sender * @param token Address of the token * @param amount Amount to recover * @return True on success */ function recover(IERC20 token, uint256 amount) external override onlyDao("EPool: not dao") returns (bool) { token.safeTransfer(msg.sender, amount); emit RecoveredToken(address(token), amount); return true; } /* ------------------------------------------------------------------------------------------------------- */ /* view and pure methods */ /* ------------------------------------------------------------------------------------------------------- */ function minInputAmountAForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 minTokenA) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); address[] memory path = new address[](2); path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); minTokenA = amountA + router.getAmountsIn(amountB, path)[0]; } // does not include price impact, which would result in a smaller EToken amount function eTokenForMinInputAmountA_Unsafe( IEPool ePool, address eToken, uint256 minInputAmountA ) external view returns (uint256 amount) { IEPool.Tranche memory t = ePool.getTranche(eToken); uint256 rate = ePool.getRate(); uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB); (uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenA( minInputAmountA, ratio, rate, sFactorA, sFactorB ); return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB); } function minInputAmountBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 minTokenB) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); address[] memory path = new address[](2); path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); minTokenB = amountB + router.getAmountsIn(amountA, path)[0]; } // does not include price impact, which would result in a smaller EToken amount function eTokenForMinInputAmountB_Unsafe( IEPool ePool, address eToken, uint256 minInputAmountB ) external view returns (uint256 amount) { IEPool.Tranche memory t = ePool.getTranche(eToken); uint256 rate = ePool.getRate(); uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB); (uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenB( minInputAmountB, ratio, rate, sFactorA, sFactorB ); return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB); } function maxOutputAmountAForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 maxTokenA) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); uint256 feeRate = ePool.feeRate(); amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI; amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI; address[] memory path = new address[](2); path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); maxTokenA = amountA + router.getAmountsOut(amountB, path)[1]; } function maxOutputAmountBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 maxTokenB) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); uint256 feeRate = ePool.feeRate(); amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI; amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI; address[] memory path = new address[](2); path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); maxTokenB = amountB + router.getAmountsOut(amountA, path)[1]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; interface IKeeperSubsidyPool { function getController() external view returns (address); function setController(address _controller) external returns (bool); function setBeneficiary(address beneficiary, bool canRequest) external returns (bool); function isBeneficiary(address beneficiary) external view returns (bool); function requestSubsidy(address token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: GNU pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GNU pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed tokenA, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // SPDX-License-Identifier: GNU pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amountA); event Burn(address indexed sender, uint amount0, uint amountA, address indexed to); event Swap( address indexed sender, uint amount0In, uint amountAIn, uint amount0Out, uint amountAOut, address indexed to ); event Sync(uint112 reserve0, uint112 reserveA); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function tokenA() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserveA, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amountA); function swap(uint amount0Out, uint amountAOut, address to, bytes calldata data) external; function skim(address to) external; function sync() external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEToken is IERC20 { function getController() external view returns (address); function setController(address _controller) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function burn(address account, uint256 amount) external returns (bool); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "./IKeeperSubsidyPool.sol"; import "./IUniswapRouterV2.sol"; import "./IUniswapFactory.sol"; import "./IEPool.sol"; interface IEPoolPeriphery { function getController() external view returns (address); function setController(address _controller) external returns (bool); function factory() external view returns (IUniswapV2Factory); function router() external view returns (IUniswapV2Router01); function ePools(address) external view returns (bool); function keeperSubsidyPool() external view returns (IKeeperSubsidyPool); function maxFlashSwapSlippage() external view returns (uint256); function setEPoolApproval(IEPool ePool, bool approval) external returns (bool); function setMaxFlashSwapSlippage(uint256 _maxFlashSwapSlippage) external returns (bool); function issueForMaxTokenA( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountA, uint256 deadline ) external returns (bool); function issueForMaxTokenB( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountB, uint256 deadline ) external returns (bool); function redeemForMinTokenA( IEPool ePool, address eToken, uint256 amount, uint256 minOutputA, uint256 deadline ) external returns (bool); function redeemForMinTokenB( IEPool ePool, address eToken, uint256 amount, uint256 minOutputB, uint256 deadline ) external returns (bool); function rebalanceWithFlashSwap(IEPool ePool, uint256 fracDelta) external returns (bool); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEToken.sol"; interface IEPool { struct Tranche { IEToken eToken; uint256 sFactorE; uint256 reserveA; uint256 reserveB; uint256 targetRatio; } function getController() external view returns (address); function setController(address _controller) external returns (bool); function tokenA() external view returns (IERC20); function tokenB() external view returns (IERC20); function sFactorA() external view returns (uint256); function sFactorB() external view returns (uint256); function getTranche(address eToken) external view returns (Tranche memory); function getTranches() external view returns(Tranche[] memory _tranches); function addTranche(uint256 targetRatio, string memory eTokenName, string memory eTokenSymbol) external returns (bool); function getAggregator() external view returns (address); function setAggregator(address oracle, bool inverseRate) external returns (bool); function rebalanceMinRDiv() external view returns (uint256); function rebalanceInterval() external view returns (uint256); function lastRebalance() external view returns (uint256); function feeRate() external view returns (uint256); function cumulativeFeeA() external view returns (uint256); function cumulativeFeeB() external view returns (uint256); function setFeeRate(uint256 _feeRate) external returns (bool); function transferFees() external returns (bool); function getRate() external view returns (uint256); function rebalance(uint256 fracDelta) external returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv); function issueExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function redeemExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "../interfaces/IController.sol"; contract ControllerMixin { event SetController(address controller); IController internal controller; constructor(IController _controller) { controller = _controller; } modifier onlyDao(string memory revertMsg) { require(msg.sender == controller.dao(), revertMsg); _; } modifier onlyDaoOrGuardian(string memory revertMsg) { require(controller.isDaoOrGuardian(msg.sender), revertMsg); _; } modifier issuanceNotPaused(string memory revertMsg) { require(controller.pausedIssuance() == false, revertMsg); _; } function _setController(address _controller) internal { controller = IController(_controller); emit SetController(_controller); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IERC20Optional.sol"; library TokenUtils { function decimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSignature("decimals()")); require(success, "TokenUtils: no decimals"); uint8 _decimals = abi.decode(data, (uint8)); return _decimals; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IETokenFactory.sol"; import "./interfaces/IEToken.sol"; import "./interfaces/IEPool.sol"; import "./utils/TokenUtils.sol"; import "./utils/Math.sol"; library EPoolLibrary { using TokenUtils for IERC20; uint256 internal constant sFactorI = 1e18; // internal scaling factor (18 decimals) /** * @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit) * currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals */ function currentRatio( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { if (t.reserveA == 0 || t.reserveB == 0) { if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio; if (t.reserveA == 0) return 0; if (t.reserveB == 0) return type(uint256).max; } return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB); } /** * @notice Returns the deviation of reserveA and reserveB from target ratio * currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity * currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity * deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio) * deltaB := deltaA * rate */ function trancheDelta( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) { rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0; deltaA = ( Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA ) / (sFactorA + (t.targetRatio * sFactorA / sFactorI)); // (convert to TokenB precision first to avoid altering deltaA) deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI; } /** * @notice Returns the sum of the tranches reserve deltas */ function delta( IEPool.Tranche[] memory ts, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { uint256 totalReserveA; int256 totalDeltaA; int256 totalDeltaB; for (uint256 i = 0; i < ts.length; i++) { totalReserveA += ts[i].reserveA; (uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta( ts[i], rate, sFactorA, sFactorB ); (totalDeltaA, totalDeltaB) = (_rChange == 0) ? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB)) : (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB)); } if (totalDeltaA > 0) { (deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1); } else { (deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0); } rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA; } /** * @notice how much EToken can be issued, redeemed for amountA and amountB * initial issuance / last redemption: sqrt(amountA * amountB) * subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply */ function eTokenForTokenATokenB( IEPool.Tranche memory t, uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256) { uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB); if (t.reserveA + t.reserveB == 0) { return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE)); } uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB); uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA); return share * t.eToken.totalSupply() / t.sFactorE; } /** * @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it * initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2 * subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B */ function tokenATokenBForEToken( IEPool.Tranche memory t, uint256 amount, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256 amountA, uint256 amountB) { if (t.reserveA + t.reserveB == 0) { uint256 amountsA = amount * sFactorA / t.sFactorE; (amountA, amountB) = tokenATokenBForTokenA( amountsA * amountsA / sFactorA , t.targetRatio, rate, sFactorA, sFactorB ); } else { uint256 eTokenTotalSupply = t.eToken.totalSupply(); if (eTokenTotalSupply == 0) return(0, 0); uint256 share = amount * t.sFactorE / eTokenTotalSupply; amountA = share * t.reserveA / t.sFactorE; amountB = share * t.reserveB / t.sFactorE; } } /** * @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio * amountA := amountBInTokenA * ratio */ function tokenAForTokenB( uint256 amountB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI; } /** * @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio * amountB := amountAInTokenB / ratio */ function tokenBForTokenA( uint256 amountA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio) * amountB := (total / (1 + ratio)) * rate */ function tokenATokenBForTokenA( uint256 _totalA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio)); amountB = (((_totalA * sFactorI / sFactorA) * rate) / (sFactorI + ratio)) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenB, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := (total * ratio) / (rate * (1 + ratio)) * amountB := total / (1 + ratio) */ function tokenATokenBForTokenB( uint256 _totalB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = ((((_totalB * sFactorI / sFactorB) * ratio) / (sFactorI + ratio)) * sFactorA) / rate; amountB = (_totalB * sFactorI) / (sFactorI + ratio); } /** * @notice Return the total value of amountA and amountB denominated in TokenA * totalA := amountA + (amountB / rate) */ function totalA( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalA) { return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI; } /** * @notice Return the total value of amountA and amountB denominated in TokenB * totalB := amountB + (amountA * rate) */ function totalB( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalB) { return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI; } /** * @notice Return the withdrawal fee for a given amount of TokenA and TokenB * feeA := amountA * feeRate * feeB := amountB * feeRate */ function feeAFeeBForTokenATokenB( uint256 amountA, uint256 amountB, uint256 feeRate ) internal pure returns (uint256 feeA, uint256 feeB) { feeA = amountA * feeRate / EPoolLibrary.sFactorI; feeB = amountB * feeRate / EPoolLibrary.sFactorI; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; interface IController { function dao() external view returns (address); function guardian() external view returns (address); function isDaoOrGuardian(address sender) external view returns (bool); function setDao(address _dao) external returns (bool); function setGuardian(address _guardian) external returns (bool); function feesOwner() external view returns (address); function pausedIssuance() external view returns (bool); function setFeesOwner(address _feesOwner) external returns (bool); function setPausedIssuance(bool _pausedIssuance) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; /** * @dev Interface of the the optional methods of the ERC20 standard as defined in the EIP. */ interface IERC20Optional { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "./IEToken.sol"; interface IETokenFactory { function getController() external view returns (address); function setController(address _controller) external returns (bool); function createEToken(string memory name, string memory symbol) external returns (IEToken); } // SPDX-License-Identifier: GNU pragma solidity ^0.8.1; library Math { function abs(uint256 a, uint256 b) internal pure returns (uint256) { return (a > b) ? a - b : b - a; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } }
Returns the address of the current Aggregator which provides the exchange rate between TokenA and TokenB return Address of aggregator/
function getController() external view override returns (address) { return address(controller); }
1,224,776
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. * * Subtraction and addition only here. */ library SafeMath { /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title A contract for generating unique identifiers for any requests. * @dev Any contract that supports requesting inherits this contract to * ensure request to be unique. */ contract RequestUid { /** * MEMBER: counter for request. */ uint256 public requestCount; /** * CONSTRUCTOR: initial counter with 0. */ constructor() public { requestCount = 0; } /** * METHOD: generate a new identifier. * @dev 3 parameters as inputs: * 1. blockhash of previous block; * 2. the address of the initialized contract which is requested; * 3. the value of counter. * @return a 32-byte uid. */ function generateRequestUid() internal returns (bytes32 uid) { return keccak256(abi.encodePacked(blockhash(block.number - uint256(1)), address(this), ++requestCount)); } } /** * @dev This contract makes the inheritor have the functionality if the * inheritor authorize the admin. */ contract AdminUpgradeable is RequestUid { /** * Event * @dev After requesting of admin change, emit an event. */ event AdminChangeRequested(bytes32 _uid, address _msgSender, address _newAdmin); /** * Event * @dev After confirming a request of admin change, emit an event. */ event AdminChangeConfirmed(bytes32 _uid, address _newAdmin); /** * STRUCT: A struct defined to store an request of admin change. */ struct AdminChangeRequest { address newAdminAddress; } /** * MEMBER: admin address(account address or contract address) which * is authorize by the inheritor. */ address public admin; /** * MEMBER: a list of requests submitted. */ mapping (bytes32 => AdminChangeRequest) public adminChangeReqs; /** * MODIFIER: The operations from admin is allowed only. */ modifier adminOperations { require(msg.sender == admin, "admin can call this method only"); _; } /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public RequestUid() { admin = _admin; } /** * METHOD: Upgrade the admin ---- request. * @dev Request changing the admin address authorized. * Anyone can call this method to submit a request to change * the admin address. It will be pending until admin address * comfirming the request, and the admin changes. * @param _newAdmin The address of new admin, account or contract. * @return uid The unique id of the request. */ function requestAdminChange(address _newAdmin) public returns (bytes32 uid) { require(_newAdmin != address(0), "admin is not 0 address"); uid = generateRequestUid(); adminChangeReqs[uid] = AdminChangeRequest({ newAdminAddress: _newAdmin }); emit AdminChangeRequested(uid, msg.sender, _newAdmin); } /** * METHOD: Upgrade the admin ---- confirm. * @dev Confirm a reqeust of admin change storing in the mapping * of `adminChangeReqs`. The operation is authorized to the old * admin only. The new admin will be authorized after the method * called successfully. * @param _uid The uid of request to change admin. */ function confirmAdminChange(bytes32 _uid) public adminOperations { admin = getAdminChangeReq(_uid); delete adminChangeReqs[_uid]; emit AdminChangeConfirmed(_uid, admin); } /** * METHOD: Get the address of an admin request by uid. * @dev It is a private method which gets address of an admin * in the mapping `adminChangeReqs` * @param _uid The uid of request to change admin. * @return _newAdminAddress The address of new admin in the pending requests */ function getAdminChangeReq(bytes32 _uid) private view returns (address _newAdminAddress) { AdminChangeRequest storage changeRequest = adminChangeReqs[_uid]; require(changeRequest.newAdminAddress != address(0)); return changeRequest.newAdminAddress; } } /** * @dev This is a contract which will be inherited by BICAProxy and BICALedger. */ contract BICALogicUpgradeable is AdminUpgradeable { /** * Event * @dev After requesting of logic contract address change, emit an event. */ event LogicChangeRequested(bytes32 _uid, address _msgSender, address _newLogic); /** * Event * @dev After confirming a request of logic contract address change, emit an event. */ event LogicChangeConfirmed(bytes32 _uid, address _newLogic); /** * STRUCT: A struct defined to store an request of Logic contract address change. */ struct LogicChangeRequest { address newLogicAddress; } /** * MEMBER: BICALogic address(a contract address) which implements logics of token. */ BICALogic public bicaLogic; /** * MEMBER: a list of requests of logic change submitted */ mapping (bytes32 => LogicChangeRequest) public logicChangeReqs; /** * MODIFIER: The call from bicaLogic is allowed only. */ modifier onlyLogic { require(msg.sender == address(bicaLogic), "only logic contract is authorized"); _; } /** * CONSTRUCTOR: Initialize with an admin address which is authorized to change * the value of bicaLogic. */ constructor (address _admin) public AdminUpgradeable(_admin) { bicaLogic = BICALogic(0x0); } /** * METHOD: Upgrade the logic contract ---- request. * @dev Request changing the logic contract address authorized. * Anyone can call this method to submit a request to change * the logic address. It will be pending until admin address * comfirming the request, and the logic contract address changes, i.e. * the value of bicaLogic changes. * @param _newLogic The address of new logic contract. * @return uid The unique id of the request. */ function requestLogicChange(address _newLogic) public returns (bytes32 uid) { require(_newLogic != address(0), "new logic address can not be 0"); uid = generateRequestUid(); logicChangeReqs[uid] = LogicChangeRequest({ newLogicAddress: _newLogic }); emit LogicChangeRequested(uid, msg.sender, _newLogic); } /** * METHOD: Upgrade the logic contract ---- confirm. * @dev Confirm a reqeust of logic contract change storing in the * mapping of `logicChangeReqs`. The operation is authorized to * the admin only. * @param _uid The uid of request to change logic contract. */ function confirmLogicChange(bytes32 _uid) public adminOperations { bicaLogic = getLogicChangeReq(_uid); delete logicChangeReqs[_uid]; emit LogicChangeConfirmed(_uid, address(bicaLogic)); } /** * METHOD: Get the address of an logic contract address request by uid. * @dev It is a private method which gets address of an address * in the mapping `adminChangeReqs` * @param _uid The uid of request to change logic contract address. * @return _newLogicAddress The address of new logic contract address * in the pending requests */ function getLogicChangeReq(bytes32 _uid) private view returns (BICALogic _newLogicAddress) { LogicChangeRequest storage changeRequest = logicChangeReqs[_uid]; require(changeRequest.newLogicAddress != address(0)); return BICALogic(changeRequest.newLogicAddress); } } /** * @dev This contract is the core contract of all logic. It links `bicaProxy` * and `bicaLedger`. It implements the issue of new amount of token, burn some * value of someone's token. */ contract BICALogic is AdminUpgradeable { using SafeMath for uint256; /** * Event * @dev After issuing an ammout of BICA, emit an event for the value of requester. */ event Requester(address _supplyAddress, address _receiver, uint256 _valueRequested); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying margin. */ event PayMargin(address _supplyAddress, address _marginAddress, uint256 _marginValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying interest. */ event PayInterest(address _supplyAddress, address _interestAddress, uint256 _interestValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying multi fee. */ event PayMultiFee(address _supplyAddress, address _feeAddress, uint256 _feeValue); /** * Event * @dev After freezing a user address, emit an event in logic contract. */ event AddressFrozenInLogic(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in logic contract. */ event AddressUnfrozenInLogic(address indexed addr); /** * MEMBER: A reference to the proxy contract. * It links the proxy contract in one direction. */ BICAProxy public bicaProxy; /** * MEMBER: A reference to the ledger contract. * It links the ledger contract in one direction. */ BICALedger public bicaLedger; /** * MODIFIER: The call from bicaProxy is allowed only. */ modifier onlyProxy { require(msg.sender == address(bicaProxy), "only the proxy contract allowed only"); _; } /** * CONSTRUCTOR: Initialize with the proxy contract address, the ledger * contract and an admin address. */ constructor (address _bicaProxy, address _bicaLedger, address _admin) public AdminUpgradeable(_admin) { bicaProxy = BICAProxy(_bicaProxy); bicaLedger = BICALedger(_bicaLedger); } /** * METHOD: `approve` operation in logic contract. * @dev Receive the call request of `approve` from proxy contract and * request approve operation to ledger contract. Need to check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function approveWithSender(address _sender, address _spender, uint256 _value) public onlyProxy returns (bool success){ require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); bicaLedger.setAllowance(_sender, _spender, _value); bicaProxy.emitApproval(_sender, _spender, _value); return true; } /** * METHOD: Core logic of the `increaseApproval` method in proxy contract. * @dev Receive the call request of `increaseApproval` from proxy contract * and request increasing value of allownce to ledger contract. Need to * check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function increaseApprovalWithSender(address _sender, address _spender, uint256 _addedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.add(_addedValue); require(newAllowance >= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of the `decreaseApproval` method in proxy contract. * @dev Receive the call request of `decreaseApproval` from proxy contract * and request decreasing value of allownce to ledger contract. Need to * check the sender and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function decreaseApprovalWithSender(address _sender, address _spender, uint256 _subtractedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.sub(_subtractedValue); require(newAllowance <= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of comfirming request of issuetoken to a specified receiver. * @dev Admin can issue an ammout of BICA only. * @param _requesterAccount The address of request account. * @param _requestValue The value of requester. * @param _marginAccount The address of margin account. * @param _marginValue The value of token to pay to margin account. * @param _interestAccount The address accepting interest. * @param _interestValue The value of interest. * @param _otherFeeAddress The address accepting multi fees. * @param _otherFeeValue The value of other fees. */ function issue(address _requesterAccount, uint256 _requestValue, address _marginAccount, uint256 _marginValue, address _interestAccount, uint256 _interestValue, address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations { require(_requesterAccount != address(0)); require(_marginAccount != address(0)); require(_interestAccount != address(0)); require(_otherFeeAddress != address(0)); require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen"); require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen"); require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen"); require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen"); uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue); uint256 supply = bicaLedger.totalSupply(); uint256 newSupply = supply.add(requestTotalValue); if (newSupply >= supply) { bicaLedger.setTotalSupply(newSupply); bicaLedger.addBalance(_marginAccount, _marginValue); bicaLedger.addBalance(_interestAccount, _interestValue); if ( _otherFeeValue > 0 ){ bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue); } bicaLedger.addBalance(_requesterAccount, _requestValue); emit Requester(msg.sender, _requesterAccount, _requestValue); emit PayMargin(msg.sender, _marginAccount, _marginValue); emit PayInterest(msg.sender, _interestAccount, _interestValue); emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue); bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue); bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue); } } /** * METHOD: Burn the specified value of the message sender's balance. * @dev Admin can call this method to burn some amount of BICA. * @param _value The amount of token to be burned. * @return success or not. */ function burn(uint256 _value) public adminOperations returns (bool success) { bool burnerFrozen = bicaLedger.getFrozenByAddress(msg.sender); require(!burnerFrozen, "Burner is frozen"); uint256 balanceOfSender = bicaLedger.balances(msg.sender); require(_value <= balanceOfSender); bicaLedger.setBalance(msg.sender, balanceOfSender.sub(_value)); bicaLedger.setTotalSupply(bicaLedger.totalSupply().sub(_value)); bicaProxy.emitTransfer(msg.sender, address(0), _value); return true; } /** * METHOD: Freeze a user address. * @dev Admin can call this method to freeze a user account. * @param _user user address. */ function freeze(address _user) public adminOperations { require(_user != address(0), "the address to be frozen cannot be 0"); bicaLedger.freezeByAddress(_user); emit AddressFrozenInLogic(_user); } /** * METHOD: Unfreeze a user address. * @dev Admin can call this method to unfreeze a user account. * @param _user user address. */ function unfreeze(address _user) public adminOperations { require(_user != address(0), "the address to be unfrozen cannot be 0"); bicaLedger.unfreezeByAddress(_user); emit AddressUnfrozenInLogic(_user); } /** * METHOD: Core logic of `transferFrom` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferFromWithSender(address _sender, address _from, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool fromFrozen = bicaLedger.getFrozenByAddress(_from); require(!fromFrozen, "`from` is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "`to` is frozen"); uint256 balanceOfFrom = bicaLedger.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = bicaLedger.allowed(_from, _sender); require(_value <= senderAllowance); bicaLedger.setBalance(_from, balanceOfFrom.sub(_value)); bicaLedger.addBalance(_to, _value); bicaLedger.setAllowance(_from, _sender, senderAllowance.sub(_value)); bicaProxy.emitTransfer(_from, _to, _value); return true; } /** * METHOD: Core logic of `transfer` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferWithSender(address _sender, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "sender is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "to is frozen"); uint256 balanceOfSender = bicaLedger.balances(_sender); require(_value <= balanceOfSender); bicaLedger.setBalance(_sender, balanceOfSender.sub(_value)); bicaLedger.addBalance(_to, _value); bicaProxy.emitTransfer(_sender, _to, _value); return true; } /** * METHOD: Core logic of `totalSupply` interface method in ERC20 token standard. */ function totalSupply() public view returns (uint256) { return bicaLedger.totalSupply(); } /** * METHOD: Core logic of `balanceOf` interface method in ERC20 token standard. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLedger.balances(_owner); } /** * METHOD: Core logic of `allowance` interface method in ERC20 token standard. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLedger.allowed(_owner, _spender); } } /** * @dev This contract is the core storage contract of ERC20 token ledger. * It defines some operations of data in the storage. */ contract BICALedger is BICALogicUpgradeable { using SafeMath for uint256; /** * MEMBER: The total supply of the token. */ uint256 public totalSupply; /** * MEMBER: The mapping of balance of users. */ mapping (address => uint256) public balances; /** * MEMBER: The mapping of allowance of users. */ mapping (address => mapping (address => uint256)) public allowed; /** * MEMBER: The mapping of frozen addresses. */ mapping(address => bool) public frozen; /** * Event * @dev After freezing a user address, emit an event in ledger contract. */ event AddressFrozen(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in ledger contract. */ event AddressUnfrozen(address indexed addr); /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin) { totalSupply = 0; } /** * METHOD: Check an address is frozen or not. * @dev check an address is frozen or not. It can be call by logic contract only. * @param _user user addree. */ function getFrozenByAddress(address _user) public view onlyLogic returns (bool frozenOrNot) { // frozenOrNot = false; return frozen[_user]; } /** * METHOD: Freeze an address. * @dev Freeze an address. It can be called by logic contract only. * @param _user user addree. */ function freezeByAddress(address _user) public onlyLogic { require(!frozen[_user], "user already frozen"); frozen[_user] = true; emit AddressFrozen(_user); } /** * METHOD: Unfreeze an address. * @dev Unfreeze an address. It can be called by logic contract only. * @param _user user addree. */ function unfreezeByAddress(address _user) public onlyLogic { require(frozen[_user], "address already unfrozen"); frozen[_user] = false; emit AddressUnfrozen(_user); } /** * METHOD: Set `totalSupply` in the ledger contract. * @dev It will be called when a new issue is confirmed. It can be called * by logic contract only. * @param _newTotalSupply The value of new total supply. */ function setTotalSupply(uint256 _newTotalSupply) public onlyLogic { totalSupply = _newTotalSupply; } /** * METHOD: Set allowance for owner to a spender in the ledger contract. * @dev It will be called when the owner modify the allowance to the * spender. It can be called by logic contract only. * @param _owner The address allow spender to spend. * @param _spender The address allowed to spend. * @param _value The limit of how much can be spent by `_spender`. */ function setAllowance(address _owner, address _spender, uint256 _value) public onlyLogic { allowed[_owner][_spender] = _value; } /** * METHOD: Set balance of the owner in the ledger contract. * @dev It will be called when the owner modify the balance of owner * in logic. It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _newBalance The balance to be set. */ function setBalance(address _owner, uint256 _newBalance) public onlyLogic { balances[_owner] = _newBalance; } /** * METHOD: Add balance of the owner in the ledger contract. * @dev It will be called when the balance of owner increases. * It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _balanceIncrease The balance to be add. */ function addBalance(address _owner, uint256 _balanceIncrease) public onlyLogic { balances[_owner] = balances[_owner].add(_balanceIncrease); } } contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @dev This contract is a viewer of ERC20 token standard. * It includes no logic and data. */ contract BICAProxy is ERC20Interface, BICALogicUpgradeable { /** * MEMBER: The name of the token. */ string public name; /** * MEMBER: The symbol of the token. */ string public symbol; /** * MEMBER: The number of decimals of the token. */ uint public decimals; /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin){ name = "BitCapital Coin"; symbol = 'BICA'; decimals = 2; } /** * METHOD: Get `totalSupply` of token. * @dev It is the standard method of ERC20. * @return The total token supply. */ function totalSupply() public view returns (uint256) { return bicaLogic.totalSupply(); } /** * METHOD: Get the balance of a owner. * @dev It is the standard method of ERC20. * @return The balance of a owner. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLogic.balanceOf(_owner); } /** * METHOD: Emit a Transfer event in proxy contract. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic { emit Transfer(_from, _to, _value); } /** * METHOD: The message sender sends some amount of token to receiver. * @dev It will call the logic contract to send some token to receiver. * It is the standard method of ERC20. * @return success or not */ function transfer(address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferWithSender(msg.sender, _to, _value); } /** * METHOD: Transfer amount of tokens from `_from` to `_to`. * @dev It is the standard method of ERC20. * @return success or not */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value); } /** * METHOD: Emit a Approval event in proxy contract. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic { emit Approval(_owner, _spender, _value); } /** * METHOD: Allow `_spender` to be able to spend `_value` token. * @dev It is the standard method of ERC20. * @return success or not */ function approve(address _spender, uint256 _value) public returns (bool success) { return bicaLogic.approveWithSender(msg.sender, _spender, _value); } /** * METHOD: Increase allowance value of message sender to `_spender`. * @return success or not */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** * METHOD: Decrease allowance value of message sender to `_spender`. * @return success or not */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** * METHOD: Return the allowance value of `_owner` to `_spender`. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLogic.allowance(_owner, _spender); } }
METHOD: Increase allowance value of message sender to `_spender`. return success or not/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue); }
2,479,154
/** *Submitted for verification at Etherscan.io on 2021-06-25 */ // File: contracts/interfaces/ISaffronBase.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; interface ISaffronBase { enum Tranche {S, AA, A} enum LPTokenType {dsec, principal} // Store values (balances, dsec, vdsec) with TrancheUint256 struct TrancheUint256 { uint256 S; uint256 AA; uint256 A; } struct epoch_params { uint256 start_date; // Time when the platform launched uint256 duration; // Duration of epoch } } // File: contracts/interfaces/ISaffronPool.sol pragma solidity ^0.7.1; interface ISaffronPool is ISaffronBase { function add_liquidity(uint256 amount, Tranche tranche) external; function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external; function get_base_asset_address() external view returns(address); function hourly_strategy(address adapter_address) external; function wind_down_epoch(uint256 epoch, uint256 amount_sfi) external; function set_governance(address to) external; function get_epoch_cycle_params() external view returns (uint256, uint256); function shutdown() external; } // File: contracts/lib/SafeMath.sol pragma solidity ^0.7.1; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/lib/IERC20.sol pragma solidity ^0.7.1; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File: contracts/lib/Context.sol pragma solidity ^0.7.1; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/lib/Address.sol pragma solidity ^0.7.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/lib/ERC20.sol pragma solidity ^0.7.1; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/lib/SafeERC20.sol pragma solidity ^0.7.1; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/SFI.sol pragma solidity ^0.7.1; contract SFI is ERC20 { using SafeERC20 for IERC20; address public governance; address public SFI_minter; uint256 public MAX_TOKENS = 100000 ether; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Initial governance is Saffron Deployer governance = msg.sender; } function mint_SFI(address to, uint256 amount) public { require(msg.sender == SFI_minter, "must be SFI_minter"); require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(to, amount); } function set_minter(address to) external { require(msg.sender == governance, "must be governance"); SFI_minter = to; } function set_governance(address to) external { require(msg.sender == governance, "must be governance"); governance = to; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } } // File: contracts/SaffronLPBalanceToken.sol pragma solidity ^0.7.1; contract SaffronLPBalanceToken is ERC20 { address public pool_address; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Set pool_address to saffron pool that created token pool_address = msg.sender; } // Allow creating new tranche tokens function mint(address to, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _mint(to, amount); } function burn(address account, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _burn(account, amount); } function set_governance(address to) external { require(msg.sender == pool_address, "must be pool"); pool_address = to; } } // File: contracts/SaffronERC20StakingPool.sol pragma solidity ^0.7.1; contract SaffronERC20StakingPool is ISaffronPool { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; // Governance (v3: add off-chain/on-chain governance) address public base_asset_address; // Base asset managed by the pool (DAI, USDT, YFI...) address public SFI_address; // SFI token uint256 public pool_principal; // Current principal balance (added minus removed) bool public _shutdown = false; // v0, v1: shutdown the pool after the final capital deploy to prevent burning funds /**** STRATEGY ****/ address public strategy; /**** EPOCHS ****/ epoch_params public epoch_cycle = epoch_params({ start_date: 1604239200, // 11/01/2020 @ 2:00pm (UTC) duration: 14 days // 1210000 seconds }); mapping(uint256=>bool) public epoch_wound_down; // True if epoch has been wound down already (governance) /**** EPOCH INDEXED STORAGE ****/ uint256[] public epoch_principal; // Total principal owned by the pool (all tranches) uint256[] public total_dsec; // Total dsec (tokens + vdsec) uint256[] public SFI_earned; // Total SFI earned (minted at wind_down_epoch) address[] public dsec_token_addresses; // Address for each dsec token address[] public principal_token_addresses; // Address for each principal token /**** SAFFRON LP TOKENS ****/ // If we just have a token address then we can look up epoch and tranche balance tokens using a mapping(address=>SaffronV1dsecInfo) // LP tokens are dsec (redeemable for interest+SFI) and principal (redeemable for base asset) tokens struct SaffronLPTokenInfo { bool exists; uint256 epoch; LPTokenType token_type; } mapping(address=>SaffronLPTokenInfo) public saffron_LP_token_info; constructor(address _strategy, address _base_asset, address _SFI_address, bool epoch_cycle_reset) { governance = msg.sender; base_asset_address = _base_asset; SFI_address = _SFI_address; strategy = _strategy; epoch_cycle.duration = (epoch_cycle_reset ? 20 minutes : 14 days); // Make testing previous epochs easier epoch_cycle.start_date = (epoch_cycle_reset ? (block.timestamp) - (4 * epoch_cycle.duration) : 1604239200); // Make testing previous epochs easier } function new_epoch(uint256 epoch, address saffron_LP_dsec_token_address, address saffron_LP_principal_token_address) public { require(epoch_principal.length == epoch, "improper new epoch"); require(msg.sender == governance, "must be governance"); epoch_principal.push(0); total_dsec.push(0); SFI_earned.push(0); dsec_token_addresses.push(saffron_LP_dsec_token_address); principal_token_addresses.push(saffron_LP_principal_token_address); // Token info for looking up epoch and tranche of dsec tokens by token contract address saffron_LP_token_info[saffron_LP_dsec_token_address] = SaffronLPTokenInfo({ exists: true, epoch: epoch, token_type: LPTokenType.dsec }); // Token info for looking up epoch and tranche of PRINCIPAL tokens by token contract address saffron_LP_token_info[saffron_LP_principal_token_address] = SaffronLPTokenInfo({ exists: true, epoch: epoch, token_type: LPTokenType.principal }); } event DsecGeneration(uint256 time_remaining, uint256 amount, uint256 dsec, address dsec_address, uint256 epoch, uint256 tranche, address user_address, address principal_token_addr); event AddLiquidity(uint256 new_pool_principal, uint256 new_epoch_principal, uint256 new_total_dsec); // LP user adds liquidity to the pool // Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S, "ERC20 pool has no tranches"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 17, "v1.17: only epoch 17 only"); // Calculate the dsec for deposited base_asset tokens uint256 dsec = amount.mul(get_seconds_until_epoch_end(epoch)); // Update pool principal eternal and epoch state pool_principal = pool_principal.add(amount); // Add base_asset token amount to pool principal total epoch_principal[epoch] = epoch_principal[epoch].add(amount); // Add base_asset token amount to principal epoch total // Update dsec and principal balance state total_dsec[epoch] = total_dsec[epoch].add(dsec); // Transfer base_asset tokens from LP to pool IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount); // Mint Saffron LP epoch 1 <base_asset_name> dsec tokens and transfer them to sender SaffronLPBalanceToken(dsec_token_addresses[epoch]).mint(msg.sender, dsec); // Mint Saffron LP epoch 1 <base_asset_name> principal tokens and transfer them to sender SaffronLPBalanceToken(principal_token_addresses[epoch]).mint(msg.sender, amount); emit DsecGeneration(get_seconds_until_epoch_end(epoch), amount, dsec, dsec_token_addresses[epoch], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch]); emit AddLiquidity(pool_principal, epoch_principal[epoch], total_dsec[epoch]); } event WindDownEpochState(uint256 previous_epoch, uint256 SFI_earned, uint256 epoch_dsec); function wind_down_epoch(uint256 epoch, uint256 amount_sfi) public override { require(msg.sender == address(strategy), "must be strategy"); require(!epoch_wound_down[epoch], "epoch already wound down"); uint256 current_epoch = get_current_epoch(); require(epoch < current_epoch, "cannot wind down future epoch"); uint256 previous_epoch = current_epoch - 1; require(block.timestamp >= get_epoch_end(previous_epoch), "can't call before epoch ended"); SFI_earned[epoch] = amount_sfi; // Total dsec uint256 epoch_dsec = total_dsec[epoch]; epoch_wound_down[epoch] = true; emit WindDownEpochState(previous_epoch, SFI_earned[epoch], epoch_dsec); } event RemoveLiquidityDsec(uint256 dsec_percent, uint256 SFI_owned); event RemoveLiquidityPrincipal(uint256 principal); function remove_liquidity(address dsec_token_address, uint256 dsec_amount, address principal_token_address, uint256 principal_amount) external override { require(dsec_amount > 0 || principal_amount > 0, "can't remove 0"); uint256 SFI_owned; uint256 dsec_percent; // Update state for removal via dsec token if (dsec_token_address != address(0x0) && dsec_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.dsec, "bad dsec address"); require(token_epoch == 17, "v1.17: bal token epoch must be 17"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); // Dsec gives user claim over a tranche's earned SFI and interest dsec_percent = dsec_amount.mul(1 ether).div(total_dsec[token_epoch]); SFI_owned = SFI_earned[token_epoch].mul(dsec_percent) / 1 ether; SFI_earned[token_epoch] = SFI_earned[token_epoch].sub(SFI_owned); total_dsec[token_epoch] = total_dsec[token_epoch].sub(dsec_amount); } // Update state for removal via principal token if (principal_token_address != address(0x0) && principal_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[principal_token_address]; require(token_info.exists, "balance token info lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.principal, "bad balance token address"); require(token_epoch == 17, "v1.17: bal token epoch must be 17"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount); pool_principal = pool_principal.sub(principal_amount); } // Transfer if (dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); sbt.burn(msg.sender, dsec_amount); IERC20(SFI_address).safeTransfer(msg.sender, SFI_owned); emit RemoveLiquidityDsec(dsec_percent, SFI_owned); } if (principal_token_address != address(0x0) && principal_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); sbt.burn(msg.sender, principal_amount); IERC20(base_asset_address).safeTransfer(msg.sender, principal_amount); emit RemoveLiquidityPrincipal(principal_amount); } require((dsec_token_address != address(0x0) && dsec_amount > 0) || (principal_token_address != address(0x0) && principal_amount > 0), "no action performed"); } function hourly_strategy(address) external pure override { return; } function shutdown() external override { require(msg.sender == strategy || msg.sender == governance, "must be strategy"); require(block.timestamp > get_epoch_end(1) - 1 days, "trying to shutdown too early"); _shutdown = true; } /*** GOVERNANCE ***/ function set_governance(address to) external override { require(msg.sender == governance, "must be governance"); governance = to; } function set_base_asset_address(address to) public { require(msg.sender == governance, "must be governance"); base_asset_address = to; } /*** TIME UTILITY FUNCTIONS ***/ function get_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)); } function get_current_epoch() public view returns (uint256) { require(block.timestamp > epoch_cycle.start_date, "before epoch 0"); return (block.timestamp - epoch_cycle.start_date) / epoch_cycle.duration; } function get_seconds_until_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp); } /*** GETTERS ***/ function get_epoch_cycle_params() external view override returns (uint256, uint256) { return (epoch_cycle.start_date, epoch_cycle.duration); } function get_base_asset_address() external view override returns(address) { return base_asset_address; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); require(_token != base_asset_address, "cannot sweep pool assets"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } function set_strategy(address to) external { require(msg.sender == governance, "must be governance"); strategy = to; } }
LP user adds liquidity to the pool Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address Calculate the dsec for deposited base_asset tokens Update pool principal eternal and epoch state Update dsec and principal balance state Transfer base_asset tokens from LP to pool Mint Saffron LP epoch 1 <base_asset_name> dsec tokens and transfer them to sender Mint Saffron LP epoch 1 <base_asset_name> principal tokens and transfer them to sender
function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S, "ERC20 pool has no tranches"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 17, "v1.17: only epoch 17 only"); uint256 dsec = amount.mul(get_seconds_until_epoch_end(epoch)); total_dsec[epoch] = total_dsec[epoch].add(dsec); IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount); SaffronLPBalanceToken(dsec_token_addresses[epoch]).mint(msg.sender, dsec); SaffronLPBalanceToken(principal_token_addresses[epoch]).mint(msg.sender, amount); emit DsecGeneration(get_seconds_until_epoch_end(epoch), amount, dsec, dsec_token_addresses[epoch], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch]); emit AddLiquidity(pool_principal, epoch_principal[epoch], total_dsec[epoch]); } event WindDownEpochState(uint256 previous_epoch, uint256 SFI_earned, uint256 epoch_dsec);
15,393,979
pragma solidity ^0.4.24; import "./DigitalMoneyManager.sol"; import "./RightsLiveRoom.sol"; import "./utils/RDDNControl.sol"; import "./modules/MultiTokenModule.sol"; /// @title RightsLiveRoomMoney /// @dev Money controller for live rooms. contract RightsLiveRoomMoney is RDDNControl, MultiTokenModule { /*** STORAGE ***/ RightsLiveRoom public liveRoom; DigitalMoneyManager moneyManager; /*** CONSTRUCTOR ***/ constructor( address _liveRoomAddr, address _digitalMoneyManagerAddr ) public { require(_liveRoomAddr != address(0)); require(_digitalMoneyManagerAddr != address(0)); liveRoom = RightsLiveRoom(_liveRoomAddr); moneyManager = DigitalMoneyManager(_digitalMoneyManagerAddr); } /*** EXTERNAL FUNCTIONS ***/ /// @dev Aadd a money id to the list of a given live room id /// @param _liveRoomId id of the live room /// @param _moneyId money id /// @param _rate rate function addPayableMoney( uint256 _liveRoomId, uint256 _moneyId, uint256 _rate ) external whenNotPaused { require(liveRoom.ownerOf(_liveRoomId) == msg.sender); require(moneyManager.ownerOf(_moneyId) != address(0)); _addRelatedToken(_liveRoomId, _moneyId, _rate); } /// @dev Update money info of a given live room id /// @param _liveRoomId id of the live room /// @param _moneyId money id /// @param _rate rate /// @param _isBase whether the token is base function updatePayableMoney( uint256 _liveRoomId, uint256 _moneyId, uint256 _rate, bool _isBase ) external whenNotPaused { require(liveRoom.ownerOf(_liveRoomId) == msg.sender); require(moneyManager.ownerOf(_moneyId) != address(0)); _updateRelatedToken(_liveRoomId, _moneyId, _rate, _isBase); } /// @dev Remove a money ID from the list of a live room id /// @param _liveRoomId id of the live room /// @param _moneyId money id function removePayableMoney(uint256 _liveRoomId, uint256 _moneyId) external whenNotPaused { require(liveRoom.ownerOf(_liveRoomId) == msg.sender); require(moneyManager.ownerOf(_moneyId) != address(0)); _removeRelatedToken(_liveRoomId, _moneyId); } /// @dev Returns money rate of the specified live room id /// @param _liveRoomId id of the live room /// @param _moneyId money id /// @return whether the token is available function moneyRateOf(uint256 _liveRoomId, uint256 _moneyId) public view returns (uint256) { require(liveRoom.ownerOf(_liveRoomId) != address(0)); require(moneyManager.ownerOf(_moneyId) != address(0)); return _rateOf(_liveRoomId, _moneyId); } /// @dev Returns whether the specified money id is payable /// @param _liveRoomId id of the live room /// @param _moneyId money id /// @return whether the token is available function isPayableMoney(uint256 _liveRoomId, uint256 _moneyId) public view returns (bool) { require(liveRoom.ownerOf(_liveRoomId) != address(0)); require(moneyManager.ownerOf(_moneyId) != address(0)); return _isRegisteredToken(_liveRoomId, _moneyId); } /// @dev Returns base money id list of the specified live room id /// @param _liveRoomId id of the live room /// @return money id list function baseMoneyOf(uint256 _liveRoomId) public view returns (uint256) { require(liveRoom.ownerOf(_liveRoomId) != address(0)); return _baseTokenOf(_liveRoomId); } /// @dev Returns money id list of the specified live room id /// @param _liveRoomId id of the live room /// @return money id list function payableMoneysOf(uint256 _liveRoomId) public view returns (uint256[]) { require(liveRoom.ownerOf(_liveRoomId) != address(0)); return _tokensOfKey(_liveRoomId); } /// @dev Calculate amount by exchange rate /// @param _liveRoomId id of the live room /// @param _moneyId id of the money /// @param _amout amount function exchangedAmountOf( uint256 _liveRoomId, uint256 _moneyId, uint256 _amout ) public view returns (uint256) { require(liveRoom.ownerOf(_liveRoomId) != address(0)); require(moneyManager.ownerOf(_moneyId) != address(0)); // calculate amount uint256 relativeAmount = moneyManager.relativeAmountOf(_moneyId, baseMoneyOf(_liveRoomId), _amout); return _exchangedAmountOf(_liveRoomId, _moneyId, relativeAmount); } }
Aadd a money id to the list of a given live room id _liveRoomId id of the live room _moneyId money id _rate rate
function addPayableMoney( uint256 _liveRoomId, uint256 _moneyId, uint256 _rate ) external whenNotPaused { require(liveRoom.ownerOf(_liveRoomId) == msg.sender); require(moneyManager.ownerOf(_moneyId) != address(0)); _addRelatedToken(_liveRoomId, _moneyId, _rate); }
12,619,832
pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import '../contracts/libraries/StringUtils.sol'; import '../contracts/libraries/SafeMath.sol'; // This is the main building block for smart contracts. contract EnergyGridUpgradeableV2 is Ownable,ERC20 { using SafeMath for uint256; // We set the 3 options players are required to choose // We set it to constant to avoid wrong typo, safer for the contract //user type //basic , premium or hybrid user string basic = "basic"; string premium = "premium"; string hybrid = "hybrid"; bool basicchosen = false; bool premiumchosen = false; bool hybridchosen = false; string userchoicename; bool setprevrewards = false; string servicechosen; // We assign state variables here string private _tokenname ="ENERGYTOKENS"; string private _tokensymbol= "ENG"; address private _owner; uint256 randNonce =0; uint256 modulus =0; uint256 _payfee=0; uint256 maxWaitTime = 100; uint256 amounttostake; uint256 prev_gridstaked; // address owner; // We decide to use the mapping instead of the struct approach // We set a struct for each grid, the users of the grid and then the information on what user information in each grid struct Grid { uint256 gridid; uint256 gridcount; } struct Users { address payable useraddress; string username; uint256 userpoint; uint256 userbalance; } struct UserInEnergyGridInfo{ uint256 energygridid; address payable usersingridaddress; bool gridfunctioning; uint256 gridreputationscore; uint256 griduserscount; uint256 duration; } // The fixed amount of tokens stored in an unsigned integer type variable. uint256 public _totalSupply = 1000000; // An address type variable is used to store ethereum accounts taken from Ownable.sol // address public owner; // A mapping is a key/value map. Here we store each account balance. // We store values that can be easy to have when we want to index values mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) private _allowances; // We have a grid check, a previous reward and the user grid info here mapping(address => mapping(bytes32 => bool)) useringridcheck; mapping(uint256 => mapping(address => uint256)) prev_rewards; mapping(uint256 => mapping(address => uint256)) usersingridinfodetail; mapping(uint256 => uint256) gridsused; mapping(address => address) usersinallgrid; mapping(address => bool)paidforgridusage; //We set into memory for cheaper access // Mapping for carrying the infors mapping(uint256=>Grid) public _energygrids; mapping(address=>Users)public userlist; mapping(uint256=>UserInEnergyGridInfo) public usersingridlist; // We set the object for our tracks Grid newenergygrid; Users newuserregistered; UserInEnergyGridInfo useringridinfo; // We push into storage Grid[] public energygridregistered; Users[] public usersregistered; UserInEnergyGridInfo[] public usersingridinfo; /**npn * Contract initialization. * * The `constructor` is executed only once when the contract is created. */ // modifier to check if caller is owner constructor(address __owner) ERC20(_tokenname, _tokensymbol ) { _owner =__owner; // Full initializations // we set the owner from Ownable _owner = owner(); _owner = __owner; balances[_owner] = _totalSupply; } /* modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == _owner , "Caller is not owner"); } */ /** * A function to transfer tokens. * * The `external` modifier makes a function *only* callable from outside * the contract. */ // We make ppayment to participate in the grid function payfee(address payable sender, uint256 amount) external payable returns(bool, bytes memory){ // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. _owner =owner(); require ( amount >= 10, "Amount not enough to play!"); // (bool sent, bytes memory data) = msg.sender.call{value: _payfee}(""); // require(sent, "Failed to send Ether"); (bool success,bytes memory data ) = _owner.call{value: _payfee}(""); require(success, "Check the amount sent as well"); paidforgridusage[sender]= true; return (success,data); } //Eventing everything function registerenergyusername(string memory _username, address payable _useraddress) external returns(string memory, address){ //If we dont want to use the modifier from Ownable.sol require(msg.sender == _owner , "Caller is not owner"); if (paidforgridusage[_useraddress] == true){ uint256 userbalance =0; userbalance = balanceOf(_useraddress); if(usersinallgrid[_useraddress] != _useraddress){ //for player who has ever played before usersinallgrid[_useraddress] =_useraddress ; // for registered player // Storing to memory newuserregistered = Users(_useraddress,_username, 0,userbalance ); userlist[_useraddress].useraddress = _useraddress; userlist[_useraddress].username = _username; userlist[_useraddress].userpoint = 0; userlist[_useraddress].userbalance = userbalance; // Storing to storage usersregistered.push(newuserregistered); return (_username,_useraddress ); } } } // Registration for grid function registergrid(uint256 _energygridid) external returns(uint256){ uint256 i =0; i++; require(msg.sender == _owner , "Caller is not owner"); uint256 energygridcount = 0; if(gridsused[_energygridid] != _energygridid){ gridsused[_energygridid] = _energygridid; newenergygrid = Grid(_energygridid,energygridcount ); // Store into memory _energygrids[_energygridid].gridid = _energygridid; _energygrids[_energygridid].gridcount = i; energygridregistered.push(newenergygrid); return (_energygridid); } } // set the grid for the user function setenergygridwithuser(uint256 _energygridid, address payable _energyuseraddress) internal returns(uint, address) { uint256 _energyusercount =0; _energyusercount++; require(msg.sender == _owner , "Caller is not Energy Grid owner"); uint256 __energygridid =0; __energygridid = _energygridid; // We set the nonce to any random number // We can set any random variable randNonce; modulus= 100000000000; __energygridid = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % modulus; require(msg.sender == _owner, "Caller is not owner"); // The list of players must be less than two require( usersingridlist[_energygridid].griduserscount < 50 == true, "Only 50 users in each energy grid"); require(usersingridinfodetail[_energygridid][_energyuseraddress] == _energygridid, "User is already a member of grid"); // We check if user is registered within id usersingridinfodetail[_energygridid][_energyuseraddress] = _energygridid; uint256 _duration = block.number + maxWaitTime; useringridinfo = UserInEnergyGridInfo(_energygridid, _energyuseraddress, false, 0,0, _duration); usersingridlist[__energygridid].energygridid = _energygridid; usersingridlist[__energygridid].usersingridaddress = _energyuseraddress; usersingridlist[__energygridid].gridfunctioning = false; usersingridlist[__energygridid].gridreputationscore = 0; usersingridlist[__energygridid].griduserscount = 0; usersingridlist[__energygridid].duration = _duration; // Setting into storage usersingridinfo.push(useringridinfo); return(_energygridid, _energyuseraddress); } function _checkuserregistered(address payable _useraddress) public returns (bool ) { require(usersinallgrid[_useraddress] == _useraddress ); return(true); } function _checkgridregistered(uint256 _energygridid) public returns (bool) { require(_energygrids[_energygridid].gridid== _energygridid,"Energy grid id does not exist" ); return(true); } function _checkuseringrid(uint256 _energygridid,address _useraddress ) public returns (bool){ require( usersingridlist[_energygridid].usersingridaddress == _useraddress,"User not fouund in grid"); return (true); } // We can choose each service function selectBasic( ) public virtual returns(bool) { if (basicchosen){ basicchosen = true; return (basicchosen); }else{ basicchosen = false; return (basicchosen); } } function selectPremium() public virtual returns(bool) { if (premiumchosen){ premiumchosen = true; return (premiumchosen); }else{ premiumchosen = false; return (premiumchosen); } } function selectHybrid( ) public virtual returns(bool){ if (hybridchosen){ hybridchosen = true; return (hybridchosen); }else{ hybridchosen = false; return (hybridchosen); } } // We can stake previous rewards gotten in the grid function stakeprevrewards( ) public virtual returns(bool) { if(setprevrewards) { setprevrewards =true; }else{ setprevrewards =false; } return (setprevrewards); } function choosegridtostake(uint256 energygridid,address payable _useraddress, uint256 _amount ) public virtual returns(uint256){ prev_gridstaked =0; prev_gridstaked=energygridid; if (stakeprevrewards( ) ==true ){ amounttostake =0; amounttostake=_amount; uint256 winnings =0; winnings = prev_rewards[energygridid][_useraddress]; require( winnings > amounttostake, " The amount requested is not enough in this grid,please check in another grid"); transfer(_owner, amounttostake); return( amounttostake); } } //Now time to connect to grid event connectogridevent(uint256 eventenergygridid, address payable _eventuseraddress, string _eventservicechosen); function connecttogrid(uint256 _energygridid, address payable _energyuseraddresss) internal returns(uint256, address, string memory){ string memory _servicechosen; // Access Controls require(msg.sender == _owner , "Caller is not owner"); _checkuserregistered(_energyuseraddresss); _checkgridregistered( _energygridid); _checkuseringrid( _energygridid ,_energyuseraddresss ); choosegridtostake(prev_gridstaked, _energyuseraddresss,amounttostake ); servicechosen = _servicechosen; if (selectBasic() == true ){ premiumchosen = false; hybridchosen = false; servicechosen = "basic" ; } if (selectPremium()== true ){ basicchosen = false; hybridchosen = false; servicechosen = "premium" ; } if (selectHybrid()== true ){ basicchosen =false; premiumchosen =false; servicechosen = "hybrid" ; } // We set a shuffler to generate a random number uint256 shuffler = 0; shuffler= 100000000; uint256 _energyindex = 0; // We set a random number, well there has to be a better way of doing this thing randNonce++; _gameindex = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % shuffler; string memory premiumpackage = "premium"; if (StringUtils.equal(servicechosen, premiumpackage)== true ){ approve( _energyuseraddresss, 100); transfer(_energyuseraddresss,100); // _owner.transfer(_theplayeraddress,10000); balanceOf(_energyuseraddresss); prev_rewards[_energygridid][_energyuseraddresss] +=100; // Whatever energy business model is necessary to be built } emit connectogridevent( _energygridid, _energyuseraddresss, servicechosen); return ( _energygridid, _energyuseraddresss, servicechosen); } // We inherit some ERC20 calls function balanceOf(address account) public view override returns (uint256) { return (balances[account]); } function owner() public view virtual override returns (address) { return (_owner); } function mint (address account, uint256 amount) external virtual returns (address, uint256 ) { _mint( msg.sender, amount); return( account, amount); } function burn (address account, uint256 amount) external virtual returns (address, uint256 ) { _burn( msg.sender , amount); return( account, amount); } function totalSupply() public view virtual override returns (uint256) { return (_totalSupply); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { // Just in case we have not transferred to sender // sender =_owner; _transfer(sender, recipient, amount); // setting allowance value here uint256 allowallowance = _allowances[sender][_msgSender()]; // 90 percent of owners balance allowed uint256 senderbalance = balances[sender]; uint256 allownacevalue =90; uint256 ninetypercent = allownacevalue /100; uint256 maximumallowance = ninetypercent * senderbalance; // We set the current allowance as that figure // uint256 currentAllowance = _allowances[sender][_msgSender()]; allowallowance =maximumallowance; uint256 currentAllowance = allowallowance; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } }
We can stake previous rewards gotten in the grid
function stakeprevrewards( ) public virtual returns(bool) { if(setprevrewards) { setprevrewards =true; setprevrewards =false; } return (setprevrewards); }else{ }
5,468,389
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import "./GenerativeBB.sol"; import "./NonGenerativeBB.sol"; contract BlindBox is NonGenerativeBB { using Counters for Counters.Counter; using SafeMath for uint256; struct Series1 { string name; string seriesURI; string boxName; string boxURI; uint256 startTime; uint256 endTime; string collection; } struct Series2 { uint256 maxBoxes; uint256 perBoxNftMint; uint256 perBoxPrice; address bankAddress; uint256 baseCurrency; uint256[] allowedCurrencies; string name; } /** @dev constructor initializing blindbox */ constructor() payable { } // add URIs/attributes in series [handled in respective BBs] function updateWhiteList(uint256 seriesId, bool isWhiteListed)onlyOwner public { _isWhiteListed[seriesId] = isWhiteListed; } // add URIs/attributes in series [handled in respective BBs] function updateNonGenSupply(uint256 seriesId, uint256 maxSupply)onlyOwner public { nonGenSeries[seriesId].maxBoxes = maxSupply; } function reduceMintedBoxSupply(uint256 seriesId)onlyOwner public { nonGenSeries[seriesId].boxId.decrement(); } /** @dev this function is to buy box of any type. @param seriesId id of the series of whom box to bought. @param isGenerative flag to show either blindbox to be bought is of Generative blindbox type or Non-Generative */ function buyBox(uint256 seriesId, bool isGenerative, uint256 currencyType, address collection, string memory ownerId, bytes32 user) public { if(isGenerative){ // buyGenerativeBox(seriesId, currencyType); } else { buyNonGenBox(seriesId, currencyType, collection, ownerId, user); } } function buyBoxPayable(uint256 seriesId, bool isGenerative, address collection, bytes32 user) payable public { if(isGenerative){ // buyGenBoxPayable(seriesId); } else { buyNonGenBoxPayable(seriesId, collection, user); } } function getPerBoxLimit(uint256 seriesId) public view returns(uint256){ return _perBoxUserLimit[seriesId]; } fallback() payable external {} receive() payable external {} event SeriesInputValue(Series1 _series, uint256 seriesId, bool isGenerative, uint256 royalty, bool whiteListOnly); event Series1InputValue(Series2 _series, uint256 seriesId, bool isGenerative); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @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. */ 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. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) internal { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRand { function getRandomNumber() external returns (bytes32 requestId); function getRandomVal() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Proxy/BlindboxStorage.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; contract Utils is Ownable, BlindboxStorage{ using Counters for Counters.Counter; using SafeMath for uint256; constructor() { } function addCryptoWhiteListUser(address[] memory _addresses, uint256 seriesId) onlyOwner public { for(uint256 i =0; i< _addresses.length; i++){ crypoWhiteList[_addresses[i]][seriesId] = true; } } function addNonCryptoWhiteListUser(string[] memory ownerIds, uint256 seriesId) onlyOwner public { for(uint256 i =0; i< ownerIds.length; i++){ nonCryptoWhiteList[ownerIds[i]][seriesId] = true; } } function removeCryptoWhiteListUser(address[] memory _addresses, uint256 seriesId) onlyOwner public { for(uint256 i =0; i< _addresses.length; i++){ crypoWhiteList[_addresses[i]][seriesId] = false; } } function removeNonCryptoWhiteListUser(string[] memory ownerIds, uint256 seriesId) onlyOwner public { for(uint256 i =0; i< ownerIds.length; i++){ nonCryptoWhiteList[ownerIds[i]][seriesId] = false; } } function calculatePrice(uint256 _price, uint256 base, uint256 currencyType) public view returns(uint256 price) { price = _price; (uint112 _reserve0, uint112 _reserve1,) =LPMATIC.getReserves(); if(currencyType == 0 && base == 1){ price = SafeMath.div(SafeMath.mul(price,SafeMath.mul(_reserve1,1000000000000)),_reserve0); } else if(currencyType == 1 && base == 0){ price = SafeMath.div(SafeMath.mul(price,_reserve0),SafeMath.mul(_reserve1,1000000000000)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '../IERC20.sol'; import '../VRF/IRand.sol'; import '../INFT.sol'; import '../IDEX.sol'; import "../LPInterface.sol"; /////////////////////////////////////////////////////////////////////////////////////////////////// /** * @title DexStorage * @dev Defining dex storage for the proxy contract. */ /////////////////////////////////////////////////////////////////////////////////////////////////// contract BlindboxStorage { using Counters for Counters.Counter; using SafeMath for uint256; address a; address b; address c; IRand vrf; IERC20 ALIA; IERC20 ETH; IERC20 USD; IERC20 MATIC; INFT nft; IDEX dex; address platform; IERC20 internal token; Counters.Counter internal _boxId; Counters.Counter public generativeSeriesId; struct Attribute { string name; string uri; uint256 rarity; } struct GenerativeBox { string name; string boxURI; uint256 series; // to track start end Time uint256 countNFTs; // uint256[] attributes; // uint256 attributesRarity; bool isOpened; } struct GenSeries { string name; string seriesURI; string boxName; string boxURI; uint256 startTime; uint256 endTime; uint256 maxBoxes; uint256 perBoxNftMint; uint256 price; // in ALIA Counters.Counter boxId; // to track series's boxId (upto minted so far) Counters.Counter attrType; // attribute Type IDs Counters.Counter attrId; // attribute's ID // attributeType => attributeId => Attribute mapping ( uint256 => mapping( uint256 => Attribute)) attributes; // attributes combination hash => flag mapping ( bytes32 => bool) blackList; } struct NFT { // attrType => attrId mapping (uint256 => uint256) attribute; } // seriesId => Series mapping ( uint256 => GenSeries) public genSeries; mapping ( uint256 => uint256) public genseriesRoyalty; mapping ( uint256 => uint256[]) _allowedCurrenciesGen; mapping ( uint256 => address) public bankAddressGen; mapping ( uint256 => uint256) public baseCurrencyGen; mapping (uint256=>string) public genCollection; // boxId => attributeType => attributeId => Attribute // mapping( uint256 => mapping ( uint256 => mapping( uint256 => Attribute))) public attributes; // boxId => Box mapping ( uint256 => GenerativeBox) public boxesGen; // attributes combination => flag // mapping ( bytes => bool) public blackList; // boxId => boxOpener => array of combinations to be minted // mapping ( uint256 => mapping ( address => bytes[] )) public nftToMint; // boxId => owner mapping ( uint256 => address ) public genBoxOwner; // boxId => NFT index => attrType => attribute mapping (uint256 => mapping( uint256 => mapping (uint256 => uint256))) public nftsToMint; Counters.Counter public nonGenerativeSeriesId; // mapping(address => Counters.Counter) public nonGenerativeSeriesIdByAddress; struct URI { string name; string uri; uint256 rarity; uint256 copies; } struct NonGenerativeBox { string name; string boxURI; uint256 series; // to track start end Time uint256 countNFTs; // uint256[] attributes; // uint256 attributesRarity; bool isOpened; } struct NonGenSeries { string collection; string name; string seriesURI; string boxName; string boxURI; uint256 startTime; uint256 endTime; uint256 maxBoxes; uint256 perBoxNftMint; uint256 price; Counters.Counter boxId; // to track series's boxId (upto minted so far) Counters.Counter attrId; // uriId => URI mapping ( uint256 => URI) uris; } struct IDs { Counters.Counter attrType; Counters.Counter attrId; } struct CopiesData{ uint256 total; mapping(uint256 => uint256) nftCopies; } mapping (uint256 => CopiesData) public _CopiesData; // seriesId => NonGenSeries mapping ( uint256 => NonGenSeries) public nonGenSeries; mapping ( uint256 => uint256[]) _allowedCurrencies; mapping ( uint256 => address) public bankAddress; mapping ( uint256 => uint256) public nonGenseriesRoyalty; mapping ( uint256 => uint256) public baseCurrency; // boxId => IDs // mapping (uint256 => IDs) boxIds; // boxId => attributeType => attributeId => Attribute // mapping( uint256 => mapping ( uint256 => mapping( uint256 => Attribute))) public attributes; // boxId => Box mapping ( uint256 => NonGenerativeBox) public boxesNonGen; // attributes combination => flag // mapping ( bytes => bool) public blackList; // boxId => boxOpener => array of combinations to be minted // mapping ( uint256 => mapping ( address => bytes[] )) public nftToMint; // boxId => owner mapping ( uint256 => address ) public nonGenBoxOwner; // boxId => NFT index => attrType => attribute // mapping (uint256 => mapping( uint256 => mapping (uint256 => uint256))) public nfts; mapping(string => mapping(bool => uint256[])) seriesIdsByCollection; uint256 deployTime; LPInterface LPAlia; LPInterface LPWETH; LPInterface LPMATIC; mapping(bytes32 => mapping(uint256 => bool)) _whitelisted; mapping(uint256 => bool) _isWhiteListed; mapping(address => mapping (uint256=>uint256)) _boxesCrytpoUser; mapping( string => mapping (uint256=>uint256)) _boxesNoncryptoUser; mapping (uint256 => uint256) _perBoxUserLimit; mapping (uint256 => bool) _isCryptoAllowed; mapping (uint256 => uint256) _registrationFee; mapping (address => mapping(uint256 => bool)) crypoWhiteList; mapping (string=> mapping(uint256 => bool)) nonCryptoWhiteList; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './GenerativeBB.sol'; contract NonGenerativeBB is GenerativeBB { using Counters for Counters.Counter; using SafeMath for uint256; /** @dev utility function to mint NonGenerative BlindBox @param seriesId - id of NonGenerative Series whose box to be opened @notice given series should not be ended or its max boxes already minted. */ function mintNonGenBox(uint256 seriesId) private { require(nonGenSeries[seriesId].startTime <= block.timestamp, "series not started"); require(nonGenSeries[seriesId].endTime >= block.timestamp, "series ended"); require(nonGenSeries[seriesId].maxBoxes > nonGenSeries[seriesId].boxId.current(),"max boxes minted of this series"); nonGenSeries[seriesId].boxId.increment(); // incrementing boxCount minted _boxId.increment(); // incrementing to get boxId boxesNonGen[_boxId.current()].name = nonGenSeries[seriesId].boxName; boxesNonGen[_boxId.current()].boxURI = nonGenSeries[seriesId].boxURI; boxesNonGen[_boxId.current()].series = seriesId; boxesNonGen[_boxId.current()].countNFTs = nonGenSeries[seriesId].perBoxNftMint; // uint256[] attributes; // attributes setting in another mapping per boxId. note: series should've all attributes [Done] // uint256 attributesRarity; // rarity should be 100, how to ensure ? //from available attrubets fill them in 100 index of array as per their rarity. divide all available rarites into 100 emit BoxMintNonGen(_boxId.current(), seriesId); } modifier validateCurrencyType(uint256 seriesId, uint256 currencyType, bool isPayable) { bool isValid = false; uint256[] storage allowedCurrencies = _allowedCurrencies[seriesId]; for (uint256 index = 0; index < allowedCurrencies.length; index++) { if(allowedCurrencies[index] == currencyType){ isValid = true; } } require(isValid, "123"); require((isPayable && currencyType == 1) || currencyType < 1, "126"); _; } /** @dev function to buy NonGenerative BlindBox @param seriesId - id of NonGenerative Series whose box to be bought @notice given series should not be ended or its max boxes already minted. */ function buyNonGenBox(uint256 seriesId, uint256 currencyType, address collection, string memory ownerId, bytes32 user) validateCurrencyType(seriesId,currencyType, false) internal { require(!_isWhiteListed[seriesId] || crypoWhiteList[msg.sender][seriesId], "not authorize"); require(abi.encodePacked(nonGenSeries[seriesId].name).length > 0,"Series doesn't exist"); require(nonGenSeries[seriesId].maxBoxes > nonGenSeries[seriesId].boxId.current(),"boxes sold out"); mintNonGenBox(seriesId); token = USD; uint256 price = calculatePrice(nonGenSeries[seriesId].price , baseCurrency[seriesId], currencyType); // if(currencyType == 0){ price = price / 1000000000000; // } // escrow alia token.transferFrom(msg.sender, bankAddress[seriesId], price); // transfer box to buyer nonGenBoxOwner[_boxId.current()] = msg.sender; emitBuyBoxNonGen(seriesId, currencyType, price, collection, ownerId); } function getUserBoxCount(uint256 seriesId, address _add, string memory ownerId) public view returns(uint256) { return _boxesCrytpoUser[_add][seriesId]; } function buyNonGenBoxPayable(uint256 seriesId, address collection, bytes32 user)validateCurrencyType(seriesId,1, true) internal { require(!_isWhiteListed[seriesId] || crypoWhiteList[msg.sender][seriesId], "not authorize"); require(abi.encodePacked(nonGenSeries[seriesId].name).length > 0,"Series doesn't exist"); require(nonGenSeries[seriesId].maxBoxes > nonGenSeries[seriesId].boxId.current(),"boxes sold out"); uint256 before_bal = MATIC.balanceOf(address(this)); MATIC.deposit{value : msg.value}(); uint256 after_bal = MATIC.balanceOf(address(this)); uint256 depositAmount = after_bal - before_bal; uint256 price = calculatePrice(nonGenSeries[seriesId].price , baseCurrency[seriesId], 1); require(price <= depositAmount, "NFT 108"); chainTransfer(bankAddress[seriesId], 1000, price); if(depositAmount - price > 0) chainTransfer(msg.sender, 1000, (depositAmount - price)); mintNonGenBox(seriesId); // transfer box to buyer nonGenBoxOwner[_boxId.current()] = msg.sender; emitBuyBoxNonGen(seriesId, 1, price, collection, ""); } function emitBuyBoxNonGen(uint256 seriesId, uint256 currencyType, uint256 price, address collection, string memory ownerId) private{ require(_boxesCrytpoUser[msg.sender][seriesId] < _perBoxUserLimit[seriesId], "Limit reach" ); _openNonGenBoxOffchain(_boxId.current(), collection); _boxesCrytpoUser[msg.sender][seriesId]++; _boxesNoncryptoUser[ownerId][seriesId]++; emit BuyBoxNonGen(_boxId.current(), seriesId, nonGenSeries[seriesId].price, currencyType, nonGenSeries[seriesId].collection, msg.sender, baseCurrency[seriesId], price); } // function chainTransfer(address _address, uint256 percentage, uint256 price) private { // address payable newAddress = payable(_address); // uint256 initialBalance; // uint256 newBalance; // initialBalance = address(this).balance; // MATIC.withdraw(SafeMath.div(SafeMath.mul(price,percentage), 1000)); // newBalance = address(this).balance.sub(initialBalance); // // newAddress.transfer(newBalance); // (bool success, ) = newAddress.call{value: newBalance}(""); // require(success, "Failed to send Ether"); // } /** @dev function to open NonGenerative BlindBox @param boxId - id of blind box to be opened @notice given box should not be already opened. */ function openNonGenBox(uint256 boxId, address collection) public { require(nonGenBoxOwner[boxId] == msg.sender, "Box not owned"); require(!boxesNonGen[boxId].isOpened, "Box already opened"); // _openNonGenBox(boxId); _openNonGenBoxOffchain(boxId, collection); emit BoxOpenedNonGen(boxId); } function _openNonGenBoxOffchain(uint256 boxId, address collection) private { uint256 sId = boxesNonGen[boxId].series; // uint256 rand = getRand(); uint256 from; uint256 to; (from, to) =dex.mintBlindbox(collection, msg.sender, boxesNonGen[boxId].countNFTs, bankAddress[sId], nonGenseriesRoyalty[sId], sId); // this function should be implemented in DEX contract to return (uint256, uint256) tokenIds, for reference look into Collection.sol mint func. (can be found at Collection/Collection.sol of same repo) boxesNonGen[boxId].isOpened = true; emit NonGenNFTsMinted(sId, boxId, from, to, 0, boxesNonGen[boxId].countNFTs); } function getNumberOfBoxes(uint256 seriesId) public view returns(uint256){ return nonGenSeries[seriesId].boxId.current(); } function updateBoxPriceNonGen(uint256 seriesId, uint256 price, uint256 _baseCurrency, uint256[] memory allowedCurrecny) onlyOwner public { baseCurrency[seriesId] = _baseCurrency; _allowedCurrencies[seriesId] = allowedCurrecny; nonGenSeries[seriesId].price = price; } function updateBoxTimeNonGen(uint256 seriesId, uint256 endTime) onlyOwner public { nonGenSeries[seriesId].endTime = endTime; } // events event BoxMintNonGen(uint256 boxId, uint256 seriesId); // event AttributesAdded(uint256 indexed boxId, uint256 indexed attrType, uint256 fromm, uint256 to); event BuyBoxNonGen(uint256 boxId, uint256 seriesId, uint256 orignalPrice, uint256 currencyType, string collection, address from,uint256 baseCurrency, uint256 calculated); event BoxOpenedNonGen(uint256 indexed boxId); // event BlackList(uint256 indexed seriesId, bytes32 indexed combHash, bool flag); event NonGenNFTsMinted(uint256 seriesId, uint256 indexed boxId, uint256 from, uint256 to, uint256 rand, uint256 countNFTs); } pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface LPInterface { /** * @dev Returns the amount of tokens in existence. */ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFT { function mintWithTokenURI(address to, string calldata tokenURI) external returns (uint256); function transferFrom(address owner, address to, uint256 tokenId) external; function mint(address to_, uint256 countNFTs_) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); function withdraw(uint) external; function deposit() payable external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IDEX { function calculatePrice(uint256 _price, uint256 base, uint256 currencyType, uint256 tokenId, address seller, address nft_a) external view returns(uint256); function mintWithCollection(address collection, address to, string memory tokesnURI, uint256 royalty ) external returns(uint256); function createCollection(string calldata name_, string calldata symbol_) external; function transferCollectionOwnership(address collection, address newOwner) external; function mintNFT(uint256 count) external returns(uint256,uint256); function mintBlindbox(address collection, address to, uint256 quantity, address from, uint256 royalty, uint256 seriesId) external returns(uint256 fromIndex,uint256 toIndex); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Utils.sol'; /** @title GenerativeBB - this contract of blindbox's type Generative. which deals with all the operations of Generative blinboxes & series */ contract GenerativeBB is Utils { using Counters for Counters.Counter; using SafeMath for uint256; constructor() { } function chainTransfer(address _address, uint256 percentage, uint256 price) internal { address payable newAddress = payable(_address); uint256 initialBalance; uint256 newBalance; initialBalance = address(this).balance; MATIC.withdraw(SafeMath.div(SafeMath.mul(price,percentage), 1000)); newBalance = address(this).balance.sub(initialBalance); // newAddress.transfer(newBalance); (bool success, ) = newAddress.call{value: newBalance}(""); require(success, "Failed to send Ether"); } }
newAddress.transfer(newBalance);
function chainTransfer(address _address, uint256 percentage, uint256 price) internal { address payable newAddress = payable(_address); uint256 initialBalance; uint256 newBalance; initialBalance = address(this).balance; MATIC.withdraw(SafeMath.div(SafeMath.mul(price,percentage), 1000)); newBalance = address(this).balance.sub(initialBalance); require(success, "Failed to send Ether"); }
10,116,737
pragma solidity 0.4.21; contract DataRegistry { enum Categories {Fingerprint, Faceshot, MissingPerson, CriminalRecord, TrafficAlert, Uncategorized} struct DataNode { uint creationts; uint reportts; uint ipfs; address reporter; Categories category; bool complete; string mimetype; } uint data_count = 0; uint completed_count = 0; uint[] ipfs_lookup; uint[] ipfs_complete; mapping(uint => DataNode) ipfs_nodes; //https://www.reddit.com/r/ethdev/comments/6lbmhy/a_practical_guide_to_cheap_ipfs_hash_storage_in/ function addData(uint _ipfs, uint _creationts, Categories _category, string _mimetype) public returns(uint) { require (ipfs_nodes[_ipfs].reportts == 0); DataNode memory dn = DataNode({creationts:_creationts, reportts:now, ipfs:_ipfs, reporter:msg.sender, category: _category, complete: false, mimetype:_mimetype}); ipfs_lookup.push(_ipfs); ipfs_nodes[_ipfs] = dn; data_count++; return data_count; } function markComplete(uint _ipfsx) public { ipfs_complete.push(_ipfsx); ipfs_nodes[_ipfsx].complete = true; completed_count++; } //returns ipfs, creationts, reportts, reporter, complete, category function getData (uint idx) public view returns(uint, uint, uint, address, Categories, bool, string) { DataNode memory _dn = ipfs_nodes[ipfs_lookup[idx]]; return (ipfs_lookup[idx], _dn.creationts, _dn.reportts, _dn.reporter, _dn.category, _dn.complete, _dn.mimetype); } function getTop () public view returns(uint){ return data_count; } function getCompletedCount() public view returns(uint) { return completed_count; } }
returns ipfs, creationts, reportts, reporter, complete, category
function getData (uint idx) public view returns(uint, uint, uint, address, Categories, bool, string) { DataNode memory _dn = ipfs_nodes[ipfs_lookup[idx]]; return (ipfs_lookup[idx], _dn.creationts, _dn.reportts, _dn.reporter, _dn.category, _dn.complete, _dn.mimetype); }
13,055,627
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; contract CPD { /// @notice EIP-20 token name for this token string public constant name = "Coinspaid"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CPD"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 800_000_000e18; // 800 million CPD /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @dev Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new CPD token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "CPD::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CPD::permit: invalid signature"); require(signatory == owner, "CPD::permit: unauthorized"); require(now <= deadline, "CPD::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "CPD::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "CPD::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CPD::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CPD::delegateBySig: invalid nonce"); require(now <= expiry, "CPD::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "CPD::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "CPD::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "CPD::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "CPD::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "CPD::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "CPD::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "CPD::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "CPD::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "CPD::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; }
11,756,602
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract ProofOfExistence { mapping(bytes32 => bool) private proofs; /// @notice store a proof of existence in the contract state /// @param proof to store function storeProof(bytes32 proof) internal { proofs[proof] = true; } /// @notice calculate and store the proof for a document /// @param document to store function notarize(string calldata document) external { bytes32 proof = proofFor(document); storeProof(proof); } /// @notice helper function to get a document's sha256 /// @param document to validate /// @return document hash function proofFor(string memory document) public pure returns (bytes32) { return keccak256(bytes(document)); } /// @notice check if a document has been notarized /// @param document to validate /// @return proof of existence function checkDocument(string memory document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); } /// @notice returns true if proof is stored /// @param proof to validate /// @return proof of existence function hasProof(bytes32 proof) internal view returns (bool) { return proofs[proof]; } }
store a proof of existence in the contract state proof to store
function storeProof(bytes32 proof) internal { proofs[proof] = true; }
14,082,092
//SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // GraffitETH is an NFT contract in which each token represents a pixel. The owner has the right // to change the pixel color. Pixel ownership is governed by the Harberger tax mechanism, i.e., // - every pixel can be bought at any time at a price the owner has to set // - the owner has to pay a tax proportional to the pixel price // // In order to facilitate tax payments, the contract manages accounts. Each account stores a // balance and the tax base. The tax base is the sum of the prices of all pixels the account owns. // It is used to calculate the tax burden (tax base * tax rate per second = tax burden per second). // The balance is increased by depositing or by selling pixels. It is decreased by withdrawing, by // paying taxes, and by buying pixels. // // The account also stores the time at which the last tax payment has been carried out. This is // used to calculate the timespan for which taxes have to be paid next time. The contract ensures // that taxes are paid whenever the balance or tax base changes. This means that the "missing" tax // is always simply tax base * tax rate * time since last tax payment. // // Account balances become negative if the deposit does not cover the tax burden. In this case, // new deposits go directly to the tax receiver's account until the account balance is zero again. // // If an account balance is negative (i.e. taxes have not been paid), the account's pixels can be // bought for free by anyone with a non-negative balance. // // All amounts and prices are stored in GWei and usually as uint64's. In order to avoid overflows, // in most cases math is carried out "clamped", i.e., if numbers would go above the maximum (or // below the minimum) we just treat them as if they would be exactly at the maximum (minimum). This // means very large or very low numbers are not necessarily accurate. However, the positive maximum // is realistically never going to be reached (it corresponds to ~18B ETH/xDai). The negative // maximum can be reached by setting a pixel price extremely high and accumulating the debt. In // this case, the clamping would save the account some taxes, but only when it's already so much // in debt that it will likely never be repaid anyway. // // The clamping math is an alternative to the usual approach of reverting transactions when numbers // run out of bounds. The latter might be a way for an owner to prevent their pixels from being // sold. // // The main exception from using clamped math is for calculating the tax base as the sum of all // pixel prices. Otherwise, one could do the following: // 1) set the price of two pixels to 2**64 - 1, meaning the tax base would be clamped // at 2**64 - 1. // 2) set the price of one of the pixels to 0, meaning the tax base is zero. Thus, // one would have to pay no taxes despite owning one pixel at price 2**64 - 1. // Instead, we revert if the sum would exceed the maximum allowed value, so that the user can // choose a lower value. // // The contract tracks the total amount of taxes an account has paid. This allows them to claim a // proportional amount of DAO shares in a separate contract. // // Freely transferring pixels is prevented as it would not only transfer value, but also the // obligation to pay taxes. Instead, we allow pixel owners to "earmark" pixels for other users. The // earmark stores the receiver's address and an additional amount. The receiver can claim any // pixel that is earmarked to them. If they do, the pixel as well as the deposit amount is // transferred to them. // // We inherit the approve and approve-for-all functionality from the ERC721 standard. Accounts that // are approved for an individual pixel can set its price and color. In addition, accounts approved // for all, have access to the approver's balance, i.e., can withdraw, buy pixels, and earmark on // their behalf. // Every user of the system gets one account that tracks their balance and tax payments. struct Account { int64 balance; uint64 taxBase; uint64 lastTaxPayment; uint64 totalTaxesPaid; } // An earmark is created by a pixel's owner and allows the receiver to claim the pixel along with // a part of their deposit. struct Earmark { address receiver; uint64 amount; } // Structs grouping arguments used to circumvent stack limit. struct PixelBuyArgs { uint256 pixelID; uint64 maxPrice; uint64 newPrice; uint8 color; } struct SetColorArgs { uint256 pixelID; uint8 newColor; } struct SetPriceArgs { uint256 pixelID; uint64 newPrice; } // RugPull is a safety hatch. It allows the owner to withdraw all funds from a contract in case of // a bug, in particular to be able to withdraw stuck funds. This action must be announced a certain // time in advance (e.g., a month, configurable) in order to allow users that don't trust the owner // to withdraw their deposits first. The safety hatch can be disabled once the contract has proven // to work reliably. // // This contract is intended to be a base from which other contracts inherit from. It does not // implement any access control, but instead exposes rugpull functions as internal functions. contract RugPull { event RugPullAnnounced( address indexed sender, uint256 timestamp, uint256 rugPullTime ); event RugPulled( address indexed sender, address indexed receiver, uint256 value ); event RugPullDisabled(address indexed sender); uint256 private _rugPullHeadsUp; uint256 private _rugPullTime; bool private _rugPullDisabled; constructor(uint256 headsUp) { // avoid overflow if heads up is chosen extremely large require(headsUp <= 5 * 365 * 24 * 60 * 60, "RugPull: heads up too big"); _rugPullHeadsUp = headsUp; _rugPullDisabled = false; _rugPullTime = 0; } function _disableRugPull() internal { require(!_rugPullDisabled, "RugPull: already disabled"); _rugPullDisabled = true; emit RugPullDisabled(msg.sender); } function _announceRugPull() internal { require(!_rugPullDisabled, "RugPull: disabled"); require(_rugPullTime == 0, "RugPull: already announced"); _rugPullTime = block.timestamp + _rugPullHeadsUp; emit RugPullAnnounced({ sender: msg.sender, timestamp: block.timestamp, rugPullTime: _rugPullTime }); } function _performRugPull(address receiver, uint256 value) internal { require(!_rugPullDisabled, "RugPull: disabled"); require(_rugPullTime != 0, "RugPull: not announced yet"); require( block.timestamp >= _rugPullTime, "RugPull: heads up not passed yet" ); (bool success, ) = receiver.call{value: value}(""); require(success, "RugPull: sending funds failed"); emit RugPulled({sender: msg.sender, receiver: receiver, value: value}); } /// @dev Get the minimum time interval in seconds between announcement and the first block at /// which the owner can perform the rug pull. function getRugPullHeadsUp() public view returns (uint256) { return _rugPullHeadsUp; } /// @dev Get the earliest timestamp at which the owner can perform the rug pull or zero if the /// rug pull has not been announced yet. function getRugPullTime() public view returns (uint256) { return _rugPullTime; } /// @dev Check if the rug pull safety hatch is disabled or not. function checkRugPullDisabled() public view returns (bool) { return _rugPullDisabled; } /// @dev Check if a rug pull has already been announced. function checkRugPullAnnounced() public view returns (bool) { return _rugPullTime != 0; } } contract GraffitETH2 is ERC721, Ownable, RugPull { // // Events // event Deposited( address indexed account, address indexed depositor, uint64 amount, int64 balance ); event Withdrawn( address indexed account, address indexed receiver, uint64 amount, int64 balance ); event ColorChanged( uint256 indexed pixelID, address indexed owner, uint8 color ); event PriceChanged( uint256 indexed pixelID, address indexed owner, uint64 price ); event Bought( uint256 indexed pixelID, address indexed seller, address indexed buyer, uint64 price ); event TaxWithdrawn(uint256 amount, address indexed receiver); event Earmarked( uint256 indexed pixelID, address indexed owner, address indexed receiver, uint64 amount ); event PixelClaimed( uint256 indexed pixelID, address indexed oldOwner, address indexed newOwner, uint64 amount ); // // State variables // // the tax rate per second is _taxRateNumerator / _taxRateDenominator uint256 private _taxRateNumerator; uint256 private _taxRateDenominator; uint64 private _taxStartTime; // timestamp before which no taxes have to be paid uint256 private _maxPixelID; // pixel ids range from 0 to _maxPixelID (inclusive) uint64 private _initialPrice; // initial price at which pixels are first sold // during initialization the owner can set owners, prices, and colors of pixels. bool private _initializing; mapping(uint256 => uint64) private _pixelPrices; mapping(address => Account) private _accounts; mapping(uint256 => Earmark) private _earmarks; uint64 private _totalInitialSaleRevenue; // amount raised for owner by selling pixels for first time uint64 private _totalTaxesPaid; // sum of all taxes paid // amount withdrawn by owner so far, both from taxes and initial sales uint64 private _totalWithdrawnByOwner; // // constructor // constructor( uint128 width, uint128 height, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime, uint64 initialPrice, uint256 rugPullHeadsUp ) ERC721("Pixel", "PXL") RugPull(rugPullHeadsUp) { require(width > 0, "GraffitETH2: width must not be zero"); require(height > 0, "GraffitETH2: height must not be zero"); // this avoids a theoretical overflow during tax computation require( taxRateNumerator <= type(uint64).max, "GraffitETH2: tax rate numerator must not be too large" ); require( taxRateDenominator > 0, "GraffitETH2: tax rate denominator must not be zero" ); _initializing = true; _maxPixelID = width * height - 1; _taxRateNumerator = taxRateNumerator; _taxRateDenominator = taxRateDenominator; _taxStartTime = taxStartTime; _initialPrice = initialPrice; } // // Getters (functions that let other random contracts and stuff read the state) // /// @dev Check if a pixel exists, i.e., has an owner. function exists(uint256 pixelID) public view returns (bool) { return _exists(pixelID); } /// @dev Get the nominal price of a pixel in GWei. The nominal price is the price at which the /// owner wants to sell it (the actual price might be different if the owner is indebted), /// or the initial price if there is no owner yet. function getNominalPrice(uint256 pixelID) public view returns (uint64) { if (!_exists(pixelID)) { return _initialPrice; } return _pixelPrices[pixelID]; } /// @dev Get the price for which anyone can buy a pixel in GWei. For non-existant pixels it is /// the initial price. For all other pixels, it is the nominal price if the owner isn't /// indebted, or zero if they are. function getPrice(uint256 pixelID) public view returns (uint64) { if (!_exists(pixelID)) { return _initialPrice; } address owner = ownerOf(pixelID); if (getBalance(owner) < 0) { return 0; } return _pixelPrices[pixelID]; } /// @dev Get the maximum valid pixel id. function getMaxPixelID() public view returns (uint256) { return _maxPixelID; } /// @dev Get the tax rate per second as nominator-denominator-tuple. function getTaxRate() public view returns (uint256, uint256) { return (_taxRateNumerator, _taxRateDenominator); } /// @dev Get the time from which on taxes have to be paid. function getTaxStartTime() public view returns (uint64) { return _taxStartTime; } /// @dev Get the initial pixel price in GWei. function getInitialPrice() public view returns (uint64) { return _initialPrice; } /// @dev Get the tax base in GWei of an account. The tax base is the sum of the nominal prices /// of all pixels owned by the account. The tax an account has to pay per time interval is /// the tax rate times the tax base. Untouched accounts have a tax base of zero. function getTaxBase(address account) public view returns (uint64) { return _accounts[account].taxBase; } /// @dev Get the time at which the last tax payment has been recorded for the given account. /// For untouched accounts, this returns zero. function getLastTaxPayment(address account) public view returns (uint64) { return _accounts[account].lastTaxPayment; } /// @dev Get the current balance of an account in GWei. This includes all tax payments up to /// now, including tax debt since lastTaxPayment, i.e., tax debt not reflected in the /// balance stored in the contract state. For untouched accounts, this returns 0. function getBalance(address account) public view returns (int64) { Account memory acc = _accounts[account]; uint64 taxPaid; (acc, taxPaid) = _payTaxes(acc); return acc.balance; } /// @dev Get the balance of the given account as it is stored in the contract. This does not /// include outstanding tax payments, so it may be greater than the actual balance. For /// untouched accounts, this returns 0. function getRecordedBalance(address account) public view returns (int64) { return _accounts[account].balance; } /// @dev Get the total money withdrawn by the owner in GWei, both from taxes and initial pixel /// sales. function getTotalWithdrawnByOwner() public view returns (uint256) { return _totalWithdrawnByOwner; } /// @dev Get the total amount of taxes paid in GWei. This only include taxes paid explicitly, /// i.e., it increases whenever the balance stored in the contract decreases due to a tax /// payment. function getTotalTaxesPaid() public view returns (uint64) { return _totalTaxesPaid; } /// @dev Get the total amount of taxes paid by the given account in GWei. This only includes /// taxes paid until the accounts's last tax payment timestamp. For untouched accounts, /// this returns 0. function getTotalTaxesPaidBy(address account) public view returns (uint64) { return _accounts[account].totalTaxesPaid; } /// @dev Get the total taxes paid of the given account in GWei, assuming an immediate tax /// payment. The amount is virtual in the sense that it cannot be withdrawn by the /// contract owner without calling payTaxes first. function getVirtualTotalTaxesPaidBy(address account) public view returns (uint64) { Account memory acc = _accounts[account]; uint64 taxPaid; (acc, taxPaid) = _payTaxes(acc); return acc.totalTaxesPaid; } /// @dev Get the maximum amount of funds (from both initial pixel sales and from taxes) in /// GWei that the owner can withdraw at the moment. function getOwnerWithdrawableAmount() public view returns (uint64) { uint64 totalRevenue = ClampedMath.addUint64(_totalTaxesPaid, _totalInitialSaleRevenue); assert(_totalWithdrawnByOwner <= totalRevenue); uint64 amount = totalRevenue - _totalWithdrawnByOwner; return amount; } /// @dev Get the total money raised by initial pixel sales in GWei. function getTotalInitialSaleRevenue() public view returns (uint256) { return _totalInitialSaleRevenue; } /// @dev Get the address for which a pixel is earmarked. For non-existent pixels or those that /// haven't been earmarked, this returns the zero address. function getEarmarkReceiver(uint256 pixelID) public view returns (address) { return _earmarks[pixelID].receiver; } /// @dev Get the amount in GWei a claimer is allowed to take over from the earmarker. For /// non-existent pixels or those that haven't been earmarked, this returns 0. function getEarmarkAmount(uint256 pixelID) public view returns (uint64) { return _earmarks[pixelID].amount; } /// @dev Check if the contract is in its initialization phase. function isInitializing() public view returns (bool) { return _initializing; } // // Public interface // /// @dev Edit the canvas by buying new pixels and changing price and color of ones already /// owned. The given buyer address must either be the sender or the sender must have been /// approved-for-all by the buyer address. Bought pixels will be transferred to the given /// buyer address. This function works for both existant and non-existant pixels. function edit( address buyerAddress, PixelBuyArgs[] memory buyArgss, SetColorArgs[] memory setColorArgss, SetPriceArgs[] memory setPriceArgss ) public { _buyMany(msg.sender, buyerAddress, buyArgss); _setColorMany(msg.sender, setColorArgss); _setPriceMany(msg.sender, setPriceArgss); } /// @dev Deposit some funds and edit the canvas by buying new pixels and changing price and /// color of ones already owned. Only the buyer address or an account approved-for-all by /// the buyer address can call this function. Deposited funds and bought pixels will go to /// the given buyer address. This function works for both existant and non-existant pixels. /// The sent amount must be a multiple of 1 GWei. function depositAndEdit( address buyerAddress, PixelBuyArgs[] memory buyArgss, SetColorArgs[] memory setColorArgss, SetPriceArgs[] memory setPriceArgss ) public payable { _depositTo(msg.sender, buyerAddress); _buyMany(msg.sender, buyerAddress, buyArgss); _setColorMany(msg.sender, setColorArgss); _setPriceMany(msg.sender, setPriceArgss); } /// @dev Explicitly update the balance of the given account to reflect tax debt for the time /// between last tax payment and now. This function can be called by anyone and in /// particular the contract owner so that they can withdraw taxes. function payTaxes(address account) public { Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); } /// @dev Deposit money to the given account. The amount sent must be a multiple of 1 GWei. function depositTo(address account) public payable { _depositTo(msg.sender, account); } /// @dev Deposit money for the sender. The amount sent must be a multiple of 1 GWei. function deposit() public payable { _depositTo(msg.sender, msg.sender); } /// @dev Withdraw an amount of GWei from the given account and send it to the given receiver /// address. Only the account itself or an account "approved for all" by the account can /// call this function. The amount must not exceed the account's current balance. function withdraw( address account, uint64 amount, address receiver ) public { _withdraw(msg.sender, account, amount, receiver); } /// @dev Withdraw the maximum possible amount of GWei from the given account and send it to /// the given receiver address. Only the account itself or an account "approved for all" /// by the owner can call this function. function withdrawMax(address account, address receiver) public { _withdrawMax(msg.sender, account, receiver); } /// @dev Withdraw a part of the taxes and income from initial sales and send it to the given /// receiver address. The withdrawal amount is specified in GWei. Only the contract /// owner is allowed to do this. function withdrawOwner(uint64 amount, address receiver) public onlyOwner { _withdrawOwner(amount, receiver); } /// @dev Withdraw all of the taxes and income from initial sales and send it to the given /// address. Only the contract owner is allowed to do this. function withdrawMaxOwner(address receiver) public onlyOwner { _withdrawOwner(getOwnerWithdrawableAmount(), receiver); } /// @dev Earmark a pixel so that the specified account can claim it. Only the pixel owner or an /// all-approved account can earmark a pixel. In addition to the pixel, the receiver can /// also claim the specified amount in GWei from the deposit. function earmark( uint256 pixelID, address receiver, uint64 amount ) public { require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "GraffitETH2: only pixel owner or approved account can set earmark" ); require(receiver != owner, "GraffitETH2: cannot earmark for owner"); _earmark(pixelID, owner, receiver, amount); } /// @dev Claim a pixel previously earmarked to the caller. This will transfer the pixel to the /// claimer, without changing price or color. In addition, a part of the deposit of the /// original owner will be transferred to the claimer's account, depending on the amount /// the earmarker allowed and their balance. The pixel is only claimed if its price in GWei /// does not exceed `maxPrice` and the transferred deposit is at least `minAmount`. function claim( uint256 pixelID, uint64 maxPrice, uint64 minAmount ) public { _claim(msg.sender, pixelID, maxPrice, minAmount); } /// @dev Freely set the initial owner, price, and color of a set of pixels. Only the owner can /// do this and only during the initialization phase. Each pixel can only be initialized /// once. function init( uint256[] memory pixelIDs, address[] memory owners, uint64[] memory prices, uint8[] memory colors ) public onlyOwner { require( _initializing, "GraffitETH2: initialization phase already over" ); uint256 n = pixelIDs.length; require( owners.length == n, "GraffitETH2: number of owners different from number of pixels" ); require( prices.length == n, "GraffitETH2: number of prices different from number of pixels" ); require( colors.length == n, "GraffitETH2: number of colors different from number of pixels" ); for (uint256 i = 0; i < n; i++) { uint256 pixelID = pixelIDs[i]; address owner = owners[i]; uint64 price = prices[i]; uint8 color = colors[i]; require( !_exists(pixelID), "GraffitETH2: pixel already initialized" ); _mint(owner, pixelID); Account memory acc = _accounts[owner]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); acc = _increaseTaxBase(acc, price); _pixelPrices[pixelID] = price; _accounts[owner] = acc; if (taxesPaid > 0) { _totalTaxesPaid = ClampedMath.addUint64( _totalTaxesPaid, taxesPaid ); } emit PriceChanged({pixelID: pixelID, owner: owner, price: price}); emit ColorChanged({pixelID: pixelID, owner: owner, color: color}); } } /// @dev Stop the initialization phase. Only the owner can do this. function stopInitialization() public onlyOwner { require( _initializing, "GraffitETH2: initialization phase already over" ); _initializing = false; } /// @dev Disable the rug pull mechanic for good. function disableRugPull() public onlyOwner { _disableRugPull(); } /// @dev Announce a rug pull to happen after the rug pull heads up. function announceRugPull() public onlyOwner { _announceRugPull(); } /// @dev Withdraw funds from contract after a rug pull has been announced. function performRugPull(address receiver, uint256 value) public onlyOwner { _performRugPull(receiver, value); } // // Internal functions // function _payTaxes(Account memory account) internal view returns (Account memory, uint64) { return Taxes.payTaxes( account, _taxRateNumerator, _taxRateDenominator, _taxStartTime ); } function _payMoreTaxes(Account memory account, uint64 taxesPaid) internal view returns (Account memory, uint64) { return Taxes.payMoreTaxes( account, taxesPaid, _taxRateNumerator, _taxRateDenominator, _taxStartTime ); } function _increaseTaxBase(Account memory account, uint64 newPixelPrice) internal pure returns (Account memory) { require( newPixelPrice <= type(uint64).max - account.taxBase, "GraffitETH2: pixel price too high, tax base max exceeded" ); account.taxBase += newPixelPrice; return account; } function _decreaseTaxBase(Account memory account, uint64 oldPixelPrice) internal pure returns (Account memory) { assert(account.taxBase >= oldPixelPrice); account.taxBase -= oldPixelPrice; return account; } function _increaseBalance( Account memory account, uint64 amount, uint64 taxesPaid ) internal pure returns (Account memory, uint64) { // if the balance is negative, the account owes taxes, so the increase in balance has to // go towards taxesPaid if (account.balance < 0) { // balance is int64 which can't represent -type(int64).min. Therefore, convert to // int256 before flipping the sign. int256 taxesOwed = -int256(account.balance); uint64 taxes; if (taxesOwed >= amount) { taxes = amount; } else { assert(taxesOwed <= type(uint64).max); // taxesOwed < amount <= uint64.max taxes = uint64(taxesOwed); } taxesPaid = ClampedMath.addUint64(taxesPaid, taxes); account.totalTaxesPaid = ClampedMath.addUint64( account.totalTaxesPaid, taxes ); } account.balance = ClampedMath.addInt64(account.balance, amount); return (account, taxesPaid); } function _decreaseBalance(Account memory account, uint64 amount) internal pure returns (Account memory) { account.balance = ClampedMath.subInt64(account.balance, amount); return account; } function _buyMany( address sender, address buyerAddress, PixelBuyArgs[] memory argss ) internal { require( sender == buyerAddress || isApprovedForAll(buyerAddress, sender), "GraffitETH2: sender is neither buyer nor approved" ); if (argss.length == 0) { return; } // Keep track of buyer and seller accounts in memory so that we can persist them to the // state eventually. This is more gas efficient than storing intermediate accounts in the // state. Account memory buyer = _accounts[buyerAddress]; uint256 numSellers = 0; // number of distinct sellers known so far address[] memory sellerAddresses = new address[](argss.length); Account[] memory sellers = new Account[](argss.length); // also keep track of taxes paid and income from initial sales uint64 taxesPaid = 0; uint64 initialSaleRevenue = 0; // pay taxes of buyer so that balance is up to date and we can safely update tax base (buyer, taxesPaid) = _payMoreTaxes(buyer, taxesPaid); for (uint256 i = 0; i < argss.length; i++) { // Make sure pixel ids are sorted and, in particular, no pixel is bought twice. require( i == 0 || argss[i].pixelID > argss[i - 1].pixelID, "GraffitETH2: pixel ids not sorted" ); uint64 price = getPrice(argss[i].pixelID); require( price <= argss[i].maxPrice, "GraffitETH2: pixel price exceeds max price" ); require( int128(buyer.balance) >= price, "GraffitETH2: buyer cannot afford pixel" ); // reduce buyer's balance and increase buyer's tax base buyer = _decreaseBalance(buyer, price); buyer = _increaseTaxBase(buyer, argss[i].newPrice); address sellerAddress; if (_exists(argss[i].pixelID)) { sellerAddress = ownerOf(argss[i].pixelID); require( sellerAddress != buyerAddress, "GraffitETH2: buyer and seller are the same" ); Account memory seller; // Find seller account in sellers array by iterating over it. We should use a // mapping here, but solidity doesn't support mappings in memory. uint256 sellerIndex; for (sellerIndex = 0; sellerIndex < numSellers; sellerIndex++) { if (sellerAddresses[sellerIndex] == sellerAddress) { seller = sellers[sellerIndex]; break; } } assert(sellerIndex <= numSellers); if (sellerIndex == numSellers) { // Seller account is not in sellers array yet, so take it from state and add it // to the array. numSellers++; seller = _accounts[sellerAddress]; sellerAddresses[sellerIndex] = sellerAddress; // Pay tax for seller so that we can safely update its balance and tax base. // We only have to do this once per seller as no time passes during execution // and thus no new tax debt accumulates. (seller, taxesPaid) = _payMoreTaxes(seller, taxesPaid); } // update seller balance and tax base uint64 oldPrice = _pixelPrices[argss[i].pixelID]; (seller, taxesPaid) = _increaseBalance( seller, price, taxesPaid ); seller = _decreaseTaxBase(seller, oldPrice); sellers[sellerIndex] = seller; // perform transfer _earmark(argss[i].pixelID, sellerAddress, address(0), 0); // cancel any earmark _transfer(sellerAddress, buyerAddress, argss[i].pixelID); } else { sellerAddress = address(0); initialSaleRevenue = ClampedMath.addUint64( initialSaleRevenue, price ); require( argss[i].pixelID <= _maxPixelID, "GraffitETH2: max pixel ID exceeded" ); _mint(buyerAddress, argss[i].pixelID); // create the pixel } // update nominal price _pixelPrices[argss[i].pixelID] = argss[i].newPrice; emit Bought({ pixelID: argss[i].pixelID, seller: sellerAddress, buyer: buyerAddress, price: price }); emit ColorChanged({ pixelID: argss[i].pixelID, owner: buyerAddress, color: argss[i].color }); emit PriceChanged({ pixelID: argss[i].pixelID, owner: buyerAddress, price: argss[i].newPrice }); } // persist account changes, taxes paid, and initial sale revenue _accounts[buyerAddress] = buyer; assert(sellerAddresses.length == sellers.length); for (uint256 i = 0; i < sellerAddresses.length; i++) { address sellerAddress = sellerAddresses[i]; _accounts[sellerAddress] = sellers[i]; } _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _totalInitialSaleRevenue = ClampedMath.addUint64( _totalInitialSaleRevenue, initialSaleRevenue ); } function _setColorMany(address sender, SetColorArgs[] memory argss) internal { for (uint256 i = 0; i < argss.length; i++) { uint256 pixelID = argss[i].pixelID; uint8 newColor = argss[i].newColor; require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); require( _isApprovedOrOwner(sender, pixelID), "GraffitETH2: only pixel owner or approved account can set color" ); emit ColorChanged({ pixelID: pixelID, owner: owner, color: newColor }); } } function _setPriceMany(address sender, SetPriceArgs[] memory argss) internal { if (argss.length == 0) { return; } address accountAddress; Account memory account; uint64 taxesPaid; for (uint256 i = 0; i < argss.length; i++) { uint256 pixelID = argss[i].pixelID; uint64 newPrice = argss[i].newPrice; require(_exists(pixelID)); address owner = ownerOf(pixelID); require( _isApprovedOrOwner(sender, pixelID), "GraffitETH2: only pixel owner or approved account can set price" ); if (i == 0) { accountAddress = owner; account = _accounts[owner]; (account, taxesPaid) = _payTaxes(account); } else { // To keep the code simple, all pixels need to be owned by the same account. // Otherwise, we'd have to keep a list of updated accounts in memory instead of // just a single one, similar to what the buy function does. It's unlikely that // someone will want to change the price of pixels owned by two or more different // accounts (possible via one or more approvals), so we can live with it. require( owner == accountAddress, "GraffitETH2: pixels owned by different accounts" ); } uint64 oldPrice = _pixelPrices[pixelID]; account = _decreaseTaxBase(account, oldPrice); account = _increaseTaxBase(account, newPrice); _pixelPrices[pixelID] = newPrice; emit PriceChanged({ pixelID: pixelID, owner: owner, price: newPrice }); } _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _accounts[accountAddress] = account; } function _depositTo(address depositor, address account) internal { if (msg.value == 0) { return; } Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); require( msg.value % (1 gwei) == 0, "GraffitETH2: deposit amount must be multiple of 1 GWei" ); uint256 valueGWei = msg.value / (1 gwei); require( valueGWei <= type(uint64).max, "GraffitETH2: max deposit amount exceeded" ); uint64 amount = uint64(valueGWei); (acc, taxesPaid) = _increaseBalance(acc, amount, taxesPaid); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); emit Deposited({ account: account, depositor: depositor, amount: amount, balance: acc.balance }); } function _withdrawMax( address sender, address account, address receiver ) internal { int64 balance = getBalance(account); require( balance >= 0, "GraffitETH2: account balance must not be negative" ); assert(int128(balance) <= type(uint64).max); uint64 amount = uint64(balance); _withdraw(sender, account, amount, receiver); } function _withdraw( address sender, address account, uint64 amount, address receiver ) internal { require( sender == account || isApprovedForAll(account, sender), "GraffitETH2: sender not allowed to withdraw" ); Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); require( int128(acc.balance) >= amount, "GraffitETH2: cannot withdraw more than balance" ); acc = _decreaseBalance(acc, amount); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); uint256 transferValue = uint256(amount) * (1 gwei); assert(transferValue / (1 gwei) == amount); (bool success, ) = receiver.call{value: transferValue}(""); require(success, "GraffitETH2: withdraw call reverted"); emit Withdrawn({ account: account, receiver: receiver, amount: amount, balance: acc.balance }); } /// @dev Earmarks a pixel. The caller should check that the pixel exists and that the current /// owner or an approved account requested the earmarking. function _earmark( uint256 pixelID, address owner, address receiver, uint64 amount ) internal { _earmarks[pixelID] = Earmark({receiver: receiver, amount: amount}); emit Earmarked({ pixelID: pixelID, owner: owner, receiver: receiver, amount: amount }); } function _withdrawOwner(uint64 amount, address receiver) internal { uint64 maxAmount = getOwnerWithdrawableAmount(); require( amount <= maxAmount, "GraffitETH2: not enough funds to withdraw" ); _totalWithdrawnByOwner = ClampedMath.addUint64( _totalWithdrawnByOwner, amount ); uint256 transferValue = uint256(amount) * (1 gwei); assert(transferValue <= address(this).balance); assert(transferValue / (1 gwei) == amount); (bool success, ) = receiver.call{value: transferValue}(""); require(success, "GraffitETH2: withdraw taxes call reverted"); emit TaxWithdrawn({amount: amount, receiver: receiver}); } function _claim( address claimer, uint256 pixelID, uint64 maxPrice, uint64 minAmount ) internal { require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); Earmark memory em = _earmarks[pixelID]; require( claimer == em.receiver, "GraffitETH2: account not allowed to claim pixel" ); uint64 taxesPaid = 0; Account memory sender = _accounts[owner]; Account memory receiver = _accounts[claimer]; (sender, taxesPaid) = _payMoreTaxes(sender, taxesPaid); (receiver, taxesPaid) = _payMoreTaxes(receiver, taxesPaid); uint64 price = getNominalPrice(pixelID); require(price <= maxPrice, "GraffitETH2: pixel is too expensive"); sender = _decreaseTaxBase(sender, price); receiver = _increaseTaxBase(receiver, price); // Transfer min(balance, em.amount) from owner to claimer, but only if it exceeds // minAmount. uint64 amount; if (int128(sender.balance) >= em.amount) { amount = em.amount; } else { if (sender.balance >= 0) { assert(int128(sender.balance) <= type(uint64).max); // balance < em.amount <= uint64.max amount = uint64(sender.balance); } else { amount = 0; } } require(amount >= minAmount, "GraffitETH2: amount is too small"); sender = _decreaseBalance(sender, amount); (receiver, taxesPaid) = _increaseBalance(receiver, amount, taxesPaid); _accounts[owner] = sender; _accounts[claimer] = receiver; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _transfer(owner, claimer, pixelID); _earmark(pixelID, owner, address(0), 0); emit PixelClaimed({ pixelID: pixelID, oldOwner: owner, newOwner: claimer, amount: amount }); } // // Transfer overrides from ERC721 // function transferFrom( address, address, uint256 ) public virtual override { assert(false); // transferring pixels is not possible } function safeTransferFrom( address, address, uint256 ) public virtual override { assert(false); // transferring pixels is not possible } function safeTransferFrom( address, address, uint256, bytes memory ) public virtual override { assert(false); // transferring pixels is not possible } } library ClampedMath { function addUint64(uint64 a, uint64 b) internal pure returns (uint64) { uint64 res; if (a <= type(uint64).max - b) { res = a + b; } else { res = type(uint64).max; } assert(res >= a && res >= b); assert(res <= uint256(a) + uint256(b)); return res; } function subUint64(uint64 a, uint64 b) internal pure returns (uint64) { uint64 res; if (a >= b) { res = a - b; } else { res = 0; } assert(res <= a); return res; } function addInt64(int64 a, uint64 b) internal pure returns (int64) { int256 resExact = int256(a) + b; int64 res; if (resExact > type(int64).max) { res = type(int64).max; } else { assert(resExact >= type(int64).min); res = int64(resExact); } assert(res >= a); return res; } function subInt64(int64 a, uint64 b) internal pure returns (int64) { int256 resExact = int256(a) - b; int64 res; if (resExact < type(int64).min) { res = type(int64).min; } else { assert(resExact <= type(int64).max); res = int64(resExact); } assert(res <= a); return res; } } library Taxes { function computeTaxes( uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxBase, uint64 startTime, uint64 endTime ) internal pure returns (uint64) { if (endTime <= startTime) { return 0; } // This doesn't overflow because each of the terms is smaller than a uint64. For the // numerator, this is ensured by the constructor of the GraffitETH2 contract. uint256 num = uint256(endTime - startTime) * uint256(taxBase) * taxRateNumerator; uint256 taxes = num / taxRateDenominator; assert(taxes <= num); uint64 res; if (taxes <= type(uint64).max) { res = uint64(taxes); } else { res = type(uint64).max; } assert(res == taxes || (taxes > res && res == type(uint64).max)); return res; } function payTaxes( Account memory acc, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime ) internal view returns (Account memory, uint64) { uint64 startTime = acc.lastTaxPayment; if (startTime < taxStartTime) { startTime = taxStartTime; } uint64 unaccountedTaxes = computeTaxes( taxRateNumerator, taxRateDenominator, acc.taxBase, startTime, uint64(block.timestamp) ); // Compute the taxes that are actually paid. This is usually just `unaccountedTax`, unless // the account cannot afford it in part or in full. uint64 taxesPaid; if (int128(acc.balance) >= unaccountedTaxes) { taxesPaid = unaccountedTaxes; } else if (acc.balance >= 0) { assert(int128(acc.balance) <= type(uint64).max); // balance < unaccountedTaxes <= uint64.max taxesPaid = uint64(acc.balance); } else { taxesPaid = 0; } assert(taxesPaid <= unaccountedTaxes); assert( (acc.balance >= 0 && taxesPaid <= int128(acc.balance)) || (acc.balance < 0 && taxesPaid == 0) ); // Update the account record acc.balance = ClampedMath.subInt64(acc.balance, unaccountedTaxes); assert(block.timestamp >= acc.lastTaxPayment); acc.lastTaxPayment = uint64(block.timestamp); acc.totalTaxesPaid = ClampedMath.addUint64( acc.totalTaxesPaid, taxesPaid ); return (acc, taxesPaid); } function payMoreTaxes( Account memory acc, uint64 taxesPaid, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime ) internal view returns (Account memory, uint64) { uint64 addedTaxes; (acc, addedTaxes) = payTaxes( acc, taxRateNumerator, taxRateDenominator, taxStartTime ); taxesPaid = ClampedMath.addUint64(taxesPaid, addedTaxes); return (acc, taxesPaid); } }
Get the price for which anyone can buy a pixel in GWei. For non-existant pixels it is the initial price. For all other pixels, it is the nominal price if the owner isn't indebted, or zero if they are.
function getPrice(uint256 pixelID) public view returns (uint64) { if (!_exists(pixelID)) { return _initialPrice; } address owner = ownerOf(pixelID); if (getBalance(owner) < 0) { return 0; } return _pixelPrices[pixelID]; }
12,773,080
./partial_match/42/0x842fDd4F71223D1F2321f2562E9678c2f1D1DE09/sources/Staking.sol
monthlyAllocation(stakeTime[msg.sender], now);
function calculateReward(address _stakeholder) public view returns(uint256) { uint256 percentageShare = SafeMath.div(SafeMath.mul(stakes[_stakeholder], 100), totalStakes()); return SafeMath.div(rewards[_stakeholder], 100); } uint256 public totalTime; uint256 public hours_staked;
3,403,483
./full_match/80001/0x089F13e85125C65052845402810B70Fbe3773c53/sources/project_/contracts/ERC721/ERC721LockableUpgradeable.sol
Approve `to` to lock operate on `tokenId` Emits a {LockApproval} event./
function _lockApprove( address owner, address to, uint256 tokenId ) internal virtual { _lockApprovals[tokenId] = to; emit LockApproval(owner, to, tokenId); }
5,652,381
/* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; import { State } from "./State.sol"; import { IInterestSetter } from "./interfaces/IInterestSetter.sol"; import { IPriceOracle } from "./interfaces/IPriceOracle.sol"; import { Account } from "./lib/Account.sol"; import { Cache } from "./lib/Cache.sol"; import { Decimal } from "./lib/Decimal.sol"; import { Interest } from "./lib/Interest.sol"; import { Monetary } from "./lib/Monetary.sol"; import { Require } from "./lib/Require.sol"; import { Storage } from "./lib/Storage.sol"; import { Token } from "./lib/Token.sol"; import { Types } from "./lib/Types.sol"; /** * @title Getters * @author dYdX * * Public read-only functions that allow transparency into the state of Solo */ contract Getters is State { using Cache for Cache.MarketCache; using Storage for Storage.State; using Types for Types.Par; // ============ Constants ============ bytes32 FILE = "Getters"; // ============ Getters for Risk ============ /** * Get the global minimum margin-ratio that every position must maintain to prevent being * liquidated. * * @return The global margin-ratio */ function getMarginRatio() public view returns (Decimal.D256 memory) { return g_state.riskParams.marginRatio; } /** * Get the global liquidation spread. This is the spread between oracle prices that incentivizes * the liquidation of risky positions. * * @return The global liquidation spread */ function getLiquidationSpread() public view returns (Decimal.D256 memory) { return g_state.riskParams.liquidationSpread; } /** * Get the global earnings-rate variable that determines what percentage of the interest paid * by borrowers gets passed-on to suppliers. * * @return The global earnings rate */ function getEarningsRate() public view returns (Decimal.D256 memory) { return g_state.riskParams.earningsRate; } /** * Get the global minimum-borrow value which is the minimum value of any new borrow on Solo. * * @return The global minimum borrow value */ function getMinBorrowedValue() public view returns (Monetary.Value memory) { return g_state.riskParams.minBorrowedValue; } /** * Get all risk parameters in a single struct. * * @return All global risk parameters */ function getRiskParams() public view returns (Storage.RiskParams memory) { return g_state.riskParams; } /** * Get all risk parameter limits in a single struct. These are the maximum limits at which the * risk parameters can be set by the admin of Solo. * * @return All global risk parameter limnits */ function getRiskLimits() public view returns (Storage.RiskLimits memory) { return g_state.riskLimits; } // ============ Getters for Markets ============ /** * Get the total number of markets. * * @return The number of markets */ function getNumMarkets() public view returns (uint256) { return g_state.numMarkets; } /** * Get the ERC20 token address for a market. * * @param marketId The market to query * @return The token address */ function getMarketTokenAddress( uint256 marketId ) public view returns (address) { _requireValidMarket(marketId); return g_state.getToken(marketId); } /** * Get the total principal amounts (borrowed and supplied) for a market. * * @param marketId The market to query * @return The total principal amounts */ function getMarketTotalPar( uint256 marketId ) public view returns (Types.TotalPar memory) { _requireValidMarket(marketId); return g_state.getTotalPar(marketId); } /** * Get the most recently cached interest index for a market. * * @param marketId The market to query * @return The most recent index */ function getMarketCachedIndex( uint256 marketId ) public view returns (Interest.Index memory) { _requireValidMarket(marketId); return g_state.getIndex(marketId); } /** * Get the interest index for a market if it were to be updated right now. * * @param marketId The market to query * @return The estimated current index */ function getMarketCurrentIndex( uint256 marketId ) public view returns (Interest.Index memory) { _requireValidMarket(marketId); return g_state.fetchNewIndex(marketId, g_state.getIndex(marketId)); } /** * Get the price oracle address for a market. * * @param marketId The market to query * @return The price oracle address */ function getMarketPriceOracle( uint256 marketId ) public view returns (IPriceOracle) { _requireValidMarket(marketId); return g_state.markets[marketId].priceOracle; } /** * Get the interest-setter address for a market. * * @param marketId The market to query * @return The interest-setter address */ function getMarketInterestSetter( uint256 marketId ) public view returns (IInterestSetter) { _requireValidMarket(marketId); return g_state.markets[marketId].interestSetter; } /** * Get the margin premium for a market. A margin premium makes it so that any positions that * include the market require a higher collateralization to avoid being liquidated. * * @param marketId The market to query * @return The market's margin premium */ function getMarketMarginPremium( uint256 marketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(marketId); return g_state.markets[marketId].marginPremium; } /** * Get the spread premium for a market. A spread premium makes it so that any liquidations * that include the market have a higher spread than the global default. * * @param marketId The market to query * @return The market's spread premium */ function getMarketSpreadPremium( uint256 marketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(marketId); return g_state.markets[marketId].spreadPremium; } /** * Return true if a particular market is in closing mode. Additional borrows cannot be taken * from a market that is closing. * * @param marketId The market to query * @return True if the market is closing */ function getMarketIsClosing( uint256 marketId ) public view returns (bool) { _requireValidMarket(marketId); return g_state.markets[marketId].isClosing; } /** * Get the price of the token for a market. * * @param marketId The market to query * @return The price of each atomic unit of the token */ function getMarketPrice( uint256 marketId ) public view returns (Monetary.Price memory) { _requireValidMarket(marketId); return g_state.fetchPrice(marketId); } /** * Get the current borrower interest rate for a market. * * @param marketId The market to query * @return The current interest rate */ function getMarketInterestRate( uint256 marketId ) public view returns (Interest.Rate memory) { _requireValidMarket(marketId); return g_state.fetchInterestRate( marketId, g_state.getIndex(marketId) ); } /** * Get the adjusted liquidation spread for some market pair. This is equal to the global * liquidation spread multiplied by (1 + spreadPremium) for each of the two markets. * * @param heldMarketId The market for which the account has collateral * @param owedMarketId The market for which the account has borrowed tokens * @return The adjusted liquidation spread */ function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public view returns (Decimal.D256 memory) { _requireValidMarket(heldMarketId); _requireValidMarket(owedMarketId); return g_state.getLiquidationSpreadForPair(heldMarketId, owedMarketId); } /** * Get basic information about a particular market. * * @param marketId The market to query * @return A Storage.Market struct with the current state of the market */ function getMarket( uint256 marketId ) public view returns (Storage.Market memory) { _requireValidMarket(marketId); return g_state.markets[marketId]; } /** * Get comprehensive information about a particular market. * * @param marketId The market to query * @return A tuple containing the values: * - A Storage.Market struct with the current state of the market * - The current estimated interest index * - The current token price * - The current market interest rate */ function getMarketWithInfo( uint256 marketId ) public view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ) { _requireValidMarket(marketId); return ( getMarket(marketId), getMarketCurrentIndex(marketId), getMarketPrice(marketId), getMarketInterestRate(marketId) ); } /** * Get the number of excess tokens for a market. The number of excess tokens is calculated * by taking the current number of tokens held in Solo, adding the number of tokens owed to Solo * by borrowers, and subtracting the number of tokens owed to suppliers by Solo. * * @param marketId The market to query * @return The number of excess tokens */ function getNumExcessTokens( uint256 marketId ) public view returns (Types.Wei memory) { _requireValidMarket(marketId); return g_state.getNumExcessTokens(marketId); } // ============ Getters for Accounts ============ /** * Get the principal value for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The principal value */ function getAccountPar( Account.Info memory account, uint256 marketId ) public view returns (Types.Par memory) { _requireValidMarket(marketId); return g_state.getPar(account, marketId); } /** * Get the token balance for a particular account and market. * * @param account The account to query * @param marketId The market to query * @return The token amount */ function getAccountWei( Account.Info memory account, uint256 marketId ) public view returns (Types.Wei memory) { _requireValidMarket(marketId); return Interest.parToWei( g_state.getPar(account, marketId), g_state.fetchNewIndex(marketId, g_state.getIndex(marketId)) ); } /** * Get the status of an account (Normal, Liquidating, or Vaporizing). * * @param account The account to query * @return The account's status */ function getAccountStatus( Account.Info memory account ) public view returns (Account.Status) { return g_state.getStatus(account); } /** * Get the total supplied and total borrowed value of an account. * * @param account The account to query * @return The following values: * - The supplied value of the account * - The borrowed value of the account */ function getAccountValues( Account.Info memory account ) public view returns (Monetary.Value memory, Monetary.Value memory) { return getAccountValuesInternal(account, /* adjustForLiquidity = */ false); } /** * Get the total supplied and total borrowed values of an account adjusted by the marginPremium * of each market. Supplied values are divided by (1 + marginPremium) for each market and * borrowed values are multiplied by (1 + marginPremium) for each market. Comparing these * adjusted values gives the margin-ratio of the account which will be compared to the global * margin-ratio when determining if the account can be liquidated. * * @param account The account to query * @return The following values: * - The supplied value of the account (adjusted for marginPremium) * - The borrowed value of the account (adjusted for marginPremium) */ function getAdjustedAccountValues( Account.Info memory account ) public view returns (Monetary.Value memory, Monetary.Value memory) { return getAccountValuesInternal(account, /* adjustForLiquidity = */ true); } /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ) { uint256 numMarkets = g_state.numMarkets; address[] memory tokens = new address[](numMarkets); Types.Par[] memory pars = new Types.Par[](numMarkets); Types.Wei[] memory weis = new Types.Wei[](numMarkets); for (uint256 m = 0; m < numMarkets; m++) { tokens[m] = getMarketTokenAddress(m); pars[m] = getAccountPar(account, m); weis[m] = getAccountWei(account, m); } return ( tokens, pars, weis ); } // ============ Getters for Permissions ============ /** * Return true if a particular address is approved as an operator for an owner's accounts. * Approved operators can act on the accounts of the owner as if it were the operator's own. * * @param owner The owner of the accounts * @param operator The possible operator * @return True if operator is approved for owner's accounts */ function getIsLocalOperator( address owner, address operator ) public view returns (bool) { return g_state.isLocalOperator(owner, operator); } /** * Return true if a particular address is approved as a global operator. Such an address can * act on any account as if it were the operator's own. * * @param operator The address to query * @return True if operator is a global operator */ function getIsGlobalOperator( address operator ) public view returns (bool) { return g_state.isGlobalOperator(operator); } // ============ Private Helper Functions ============ /** * Revert if marketId is invalid. */ function _requireValidMarket( uint256 marketId ) private view { Require.that( marketId < g_state.numMarkets, FILE, "Market OOB" ); } /** * Private helper for getting the monetary values of an account. */ function getAccountValuesInternal( Account.Info memory account, bool adjustForLiquidity ) private view returns (Monetary.Value memory, Monetary.Value memory) { uint256 numMarkets = g_state.numMarkets; // populate cache Cache.MarketCache memory cache = Cache.create(numMarkets); for (uint256 m = 0; m < numMarkets; m++) { if (!g_state.getPar(account, m).isZero()) { cache.addMarket(g_state, m); } } return g_state.getAccountValues(account, cache, adjustForLiquidity); } }
Get the principal value for a particular account and market. account The account to query marketId The market to query return The principal value/
function getAccountPar( Account.Info memory account, uint256 marketId ) public view returns (Types.Par memory) { _requireValidMarket(marketId); return g_state.getPar(account, marketId); }
979,758
/** *Submitted for verification at Etherscan.io on 2021-11-14 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/GDAOBar.sol pragma solidity 0.6.12; abstract contract GDAOBar is ERC20, Ownable{ using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public GDAO; uint256 public lockPeriod; // user address to last deposit timestamp mapping mapping(address => uint256) public depositTimestamp; constructor(address _gdao, uint _lockPeriod) public ERC20("GDAO governance","xGDAO") Ownable(){ GDAO = IERC20(_gdao); lockPeriod = _lockPeriod; } /// @dev update deposit lock period, only controller can call this function. function updateLockPeriod(uint256 _newLockPeriod) external onlyOwner { lockPeriod = _newLockPeriod; } function enter(uint256 _amount) external virtual { depositTimestamp[msg.sender] = block.timestamp; // Gets the amount of GDAO locked in the contract uint256 totalGDAO = GDAO.balanceOf(address(this)); // Gets the amount of GDAO in existence uint256 totalShares = totalSupply(); GDAO.transferFrom(msg.sender, address(this), _amount); uint256 mintAmount = (totalShares == 0 || totalGDAO == 0) ? _amount : _amount.mul(totalShares).div(totalGDAO); _mint(msg.sender, mintAmount); } function leave(uint256 _share) external { uint256 fee; uint256 senderDepositTimestamp = depositTimestamp[msg.sender]; if(block.timestamp >= senderDepositTimestamp + lockPeriod){ uint dayCount = (block.timestamp - senderDepositTimestamp - lockPeriod) / 86400; if(dayCount < 10){ fee = 10 - dayCount; } } // Calculates the amount of GDAO the xGDAO is worth uint256 amm = getPrice(_share); fee = _getWithdrawalFee(amm, fee); _burn(msg.sender, _share); GDAO.transfer(msg.sender, amm.sub(fee)); } /// @dev function returns the ammount of xGDAO some _share of GDAO is worth function getPrice(uint256 _share) public view returns(uint256){ if(totalSupply() > 0){ return _share.mul(GDAO.balanceOf(address(this))).div(totalSupply()); }else{ return 0; } } // @dev returns the withdrawalFee for a share function _getWithdrawalFee(uint256 _share, uint256 _fee) internal pure returns(uint256){ return((_share.mul(_fee)).div(100)); } } // File: contracts/PoolShareGovernanceToken.sol // From https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity 0.6.12; // solhint-disable reason-string, no-empty-blocks abstract contract PoolShareGovernanceToken is GDAOBar { /// @dev A record of each accounts delegate mapping(address => address) public delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @dev Constructor. */ constructor( address _token, uint256 _lockPeriod ) public GDAOBar(_token, _lockPeriod) {} /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( keccak256(bytes(name())), keccak256(bytes("1")), getChainId(), address(this) ) ); bytes32 structHash = keccak256(abi.encode(delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VSP::delegateBySig: invalid signature"); require(now <= expiry, "VSP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VSP::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VSP::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } // File: contracts/interfaces/uniswap/IUniswapV2Router01.sol pragma solidity 0.6.12; interface IUniswapV2Router01 { function factory() external pure returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File: contracts/interfaces/uniswap/IUniswapV2Router02.sol pragma solidity 0.6.12; interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File: address-list/contracts/interfaces/IAddressList.sol pragma solidity ^0.6.6; interface IAddressList { event AddressUpdated(address indexed a, address indexed sender); event AddressRemoved(address indexed a, address indexed sender); function add(address a) external returns (bool); function addValue(address a, uint256 v) external returns (bool); function addMulti(address[] calldata addrs) external returns (uint256); function addValueMulti(address[] calldata addrs, uint256[] calldata values) external returns (uint256); function remove(address a) external returns (bool); function removeMulti(address[] calldata addrs) external returns (uint256); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function at(uint256 index) external view returns (address, uint256); function length() external view returns (uint256); } // File: contracts/interfaces/IController.sol pragma solidity 0.6.12; interface IController { function aaveReferralCode() external view returns (uint16); function feeCollector(address) external view returns (address); function founderFee() external view returns (uint256); function founderVault() external view returns (address); function interestFee(address) external view returns (uint256); function isPool(address) external view returns (bool); function pools() external view returns (address); function strategy(address) external view returns (address); function rebalanceFriction(address) external view returns (uint256); function poolRewards(address) external view returns (address); function treasuryPool() external view returns (address); function uniswapRouter() external view returns (address); function withdrawFee(address) external view returns (uint256); } // File: contracts/xGDAO.sol pragma solidity 0.6.12; interface IStrategy { function rebalance() external; } //solhint-disable no-empty-blocks, reason-string contract xGDAO is PoolShareGovernanceToken { uint256 internal constant MAX_UINT_VALUE = uint256(-1); address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal POE; uint8 public POE_TAX; IAddressList public immutable pools; IController public controller; constructor(address _controller, address _token, address _POE, uint8 _poeTax, uint256 _lockPeriod) public PoolShareGovernanceToken(_token, _lockPeriod) { controller = IController(_controller); pools = IAddressList(IController(_controller).pools()); POE = _POE; setPoeTax(_poeTax); } modifier onlyController() { require(address(controller) == _msgSender(), "Caller is not the controller"); _; } /// @dev Approve strategy for given pool function approvePool(address pool, address strategy) external onlyController { require(pools.contains(pool), "Not a pool"); require(strategy == controller.strategy(address(this)), "Not a strategy"); IERC20(pool).safeApprove(strategy, MAX_UINT_VALUE); } /** * @dev Controller will call this function when new strategy is added in pool. * Approve strategy for all tokens */ function approveToken() external onlyController { _approve(MAX_UINT_VALUE); } /// @dev can set POE Tax function setPoeTax(uint8 _new) public onlyOwner(){ require(_new <= 100, "Cannot set POE Tax > 100"); POE_TAX = _new; } /// @dev set POE Contract address function setPOEContractAddress(address _new) external onlyOwner{ POE = _new; } /// @dev override enter to tax 2% if user does not have a POE token. /// NOTE user must APPROVE this extra 2%, we can't just take it function enter(uint256 _amount) public override{ depositTimestamp[msg.sender] = block.timestamp; // Gets the amount of GDAO locked in the contract uint256 totalGDAO = GDAO.balanceOf(address(this)); // Gets the amount of GDAO in existence uint256 totalShares = totalSupply(); // If no GDAO exists, mint it 1:1 to the amount put in if(totalGDAO > 0 && IERC20(POE).balanceOf(msg.sender) != 1){ totalGDAO = (totalGDAO * (100 + POE_TAX)) / 100; } if (totalShares == 0 || totalGDAO == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalGDAO); _mint(msg.sender, what); } GDAO.transferFrom(msg.sender, address(this), _amount); } /** * @dev Controller will call this function when strategy is removed from pool. * Reset approval of all tokens */ function resetApproval() external onlyController { _approve(uint256(0)); } function rebalance() external { IStrategy strategy = IStrategy(controller.strategy(address(this))); strategy.rebalance(); } function sweepErc20(address _erc20) external { require( _erc20 != address(GDAO) && _erc20 != address(this) && !controller.isPool(_erc20), "Not allowed to sweep" ); IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter()); IERC20 erc20 = IERC20(_erc20); uint256 amt = erc20.balanceOf(address(this)); erc20.safeApprove(address(uniswapRouter), 0); erc20.safeApprove(address(uniswapRouter), amt); address[] memory path; if (address(_erc20) == WETH) { path = new address[](2); path[0] = address(_erc20); path[1] = address(GDAO); } else { path = new address[](3); path[0] = address(_erc20); path[1] = address(WETH); path[2] = address(GDAO); } uniswapRouter.swapExactTokensForTokens(amt, 1, path, address(this), now + 30); } function changeController(address _newController) external onlyOwner{ controller = IController(_newController); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { if (from == address(0)) { // Token being minted i.e. user is depositing VSP // NOTE: here 'to' is same as 'msg.sender' depositTimestamp[to] = block.timestamp; } else { // transfer, transferFrom or withdraw is called. require( block.timestamp >= depositTimestamp[from].add(lockPeriod), "Operation not allowed due to lock period" ); } // Move vVSP delegation when mint, burn, transfer or transferFrom is called. _moveDelegates(delegates[from], delegates[to], amount); } function _approve(uint256 approvalAmount) private { address strategy = controller.strategy(address(this)); uint256 length = pools.length(); for (uint256 i = 0; i < length; i++) { (address pool, ) = pools.at(i); IERC20(pool).safeApprove(strategy, approvalAmount); } } }
function returns the ammount of xGDAO some _share of GDAO is worth
function getPrice(uint256 _share) public view returns(uint256){ if(totalSupply() > 0){ return _share.mul(GDAO.balanceOf(address(this))).div(totalSupply()); return 0; } }
15,358,307
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ // File: libs/BasicMetaTransaction.sol pragma solidity ^0.8.0; contract BasicMetaTransaction { event MetaTransactionExecuted(address userAddress, address payable relayerAddress, bytes functionSignature); mapping(address => uint256) private nonces; /** * Main function to be called when user wants to execute meta transaction. * The actual function to be called should be passed as param with name functionSignature * Here the basic signature recovery is being used. Signature is expected to be generated using * personal_sign method. * @param userAddress Address of user trying to do meta transaction * @param functionSignature Signature of the actual function to be called via meta transaction * @param sigR R part of the signature * @param sigS S part of the signature * @param sigV V part of the signature */ function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { require( verify(userAddress, nonces[userAddress], block.chainid, functionSignature, sigR, sigS, sigV), "Signer and signature do not match" ); nonces[userAddress] += 1; // Append userAddress at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "Function call not successful"); emit MetaTransactionExecuted(userAddress, payable(msg.sender), functionSignature); return returnData; } function getNonce(address user) external view returns (uint256 nonce) { nonce = nonces[user]; } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function verify( address owner, uint256 nonce, uint256 chainID, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public view returns (bool) { bytes32 hash = prefixed(keccak256(abi.encodePacked(nonce, this, chainID, functionSignature))); address signer = ecrecover(hash, sigV, sigR, sigS); require(signer != address(0), "Invalid signature"); return (owner == signer); } function msgSender() internal view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } } else { return msg.sender; } } } // File: libs/TransferHelper.sol pragma solidity 0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); } } // File: interfaces/IExchangeAgent.sol pragma solidity ^0.8.0; interface IExchangeAgent { function getNeededTokenAmount( address _token0, address _token1, uint256 _desiredAmount ) external returns (uint256); function getTokenAmountForUSDC(address _token, uint256 _desiredAmount) external returns (uint256); function getETHAmountForUSDC(uint256 _desiredAmount) external view returns (uint256); function getTokenAmountForETH(address _token, uint256 _desiredAmount) external returns (uint256); function swapTokenWithETH( address _token, uint256 _amount, uint256 _desiredAmount ) external; function swapTokenWithToken( address _token0, address _token1, uint256 _amount, uint256 _desiredAmount ) external; } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: offchain/BaseCoverOffChain.sol pragma solidity ^0.8.0; contract BaseCoverOffChain is Ownable, Pausable, BasicMetaTransaction { using Counters for Counters.Counter; event BuyProduct(uint256 indexed _productId, address _buyer); event SetExchangeAgent(address _setter, address _exchangeAgent); event SetSigner(address _setter, address _signer); Counters.Counter public productIds; mapping(uint256 => address) private _ownerOf; // productId => owner mapping(address => uint64) private _balanceOf; // owner => balance We can think one user can buy max 2**64 products mapping(address => uint64[]) private _productsOf; // owner => productIds[] mapping(address => bool) public availableCurrencies; address public immutable WETH; address public exchangeAgent; address public devWallet; address public signer; constructor( address _WETH, address _exchangeAgent, address _devWallet, address _signer ) { WETH = _WETH; exchangeAgent = _exchangeAgent; devWallet = _devWallet; signer = _signer; } modifier onlyAvailableToken(address _token) { require(availableCurrencies[_token], "Not allowed token"); _; } function setExchangeAgent(address _exchangeAgent) external onlyOwner { require(_exchangeAgent != address(0), "ZERO Address"); exchangeAgent = _exchangeAgent; emit SetExchangeAgent(msgSender(), _exchangeAgent); } function setSigner(address _signer) external onlyOwner { require(_signer != address(0), "ZERO Address"); signer = _signer; emit SetSigner(msgSender(), _signer); } function _setProductOwner(uint256 _prodId, address _owner) internal { _ownerOf[_prodId] = _owner; } function ownerOf(uint256 _prodId) public view returns (address) { require(_prodId < productIds.current() + 1, "Invalid product ID"); return _ownerOf[_prodId]; } function _increaseBalance(address _account) internal { _balanceOf[_account]++; } function balanceOf(address _account) public view returns (uint64) { return _balanceOf[_account]; } function _buyProduct(address _buyer, uint256 _pid) internal { _productsOf[_buyer].push(uint64(_pid)); emit BuyProduct(_pid, _buyer); } function productOf(address _owner, uint64 _idx) public view returns (uint64) { return _productsOf[_owner][_idx]; } function addCurrency(address _currency) external onlyOwner { require(!availableCurrencies[_currency], "Already available"); availableCurrencies[_currency] = true; } function removeCurrency(address _currency) external onlyOwner { require(availableCurrencies[_currency], "Not available yet"); availableCurrencies[_currency] = false; } function permit( address _sender, bytes32 _digest, bytes memory sig ) internal pure virtual { (bytes32 r, bytes32 s, uint8 v) = splitSignature(sig); address recoveredAddress = ecrecover(_digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == _sender, "CoverCompared: INVALID_SIGNATURE"); } function splitSignature(bytes memory sig) private pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(sig.length == 65, "invalid signature length"); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } // implicitly return (r, s, v) } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } } // File: offchain/P4LCover.sol pragma solidity ^0.8.0; contract P4LCover is Ownable, ReentrancyGuard, BaseCoverOffChain { event BuyP4L(uint256 indexed _productId, address _buyer, address _currency, uint256 _amount, uint256 _priceInUSD); using Counters for Counters.Counter; struct Product { uint256 startTime; uint128 priceInUSD; // price in USD uint128 durPlan; string policyId; } mapping(uint256 => Product) public products; // productId => product constructor( address _WETH, address _exchangeAgent, address _devWallet, address _signer ) BaseCoverOffChain(_WETH, _exchangeAgent, _devWallet, _signer) {} /** * @dev buyProductETH function: * this function should be called from user directly */ function buyProductByETH( string memory _policyId, uint256 _value, // price in USD uint256 _durPlan, bytes memory sig ) external payable nonReentrant whenNotPaused { bytes32 digest = getSignedMsgHash(_policyId, _value, _durPlan); permit(signer, digest, sig); uint256 tokenAmount = IExchangeAgent(exchangeAgent).getETHAmountForUSDC(_value); require(msg.value >= tokenAmount, "Insufficient amount"); if (msg.value > tokenAmount) { TransferHelper.safeTransferETH(msgSender(), msg.value - tokenAmount); } TransferHelper.safeTransferETH(devWallet, tokenAmount); uint256 _pid = buyProduct(uint128(_value), uint128(_durPlan), _policyId, msgSender()); emit BuyP4L(_pid, msgSender(), WETH, tokenAmount, _value); } /** * @dev buyProductByToken: Users can buy products using ERC20 tokens such as CVR and without gas fee */ function buyProductByToken( string memory _policyId, uint256 _value, uint256 _durPlan, address _token, bytes memory sig ) external nonReentrant whenNotPaused onlyAvailableToken(_token) { bytes32 digest = getSignedMsgHash(_policyId, _value, _durPlan); permit(signer, digest, sig); uint256 tokenAmount = IExchangeAgent(exchangeAgent).getTokenAmountForUSDC(_token, _value); TransferHelper.safeTransferFrom(_token, msgSender(), devWallet, tokenAmount); uint256 _pid = buyProduct(uint128(_value), uint128(_durPlan), _policyId, msgSender()); emit BuyP4L(_pid, msgSender(), _token, tokenAmount, _value); } function buyProduct( uint128 _value, uint128 _durPlan, string memory _policyId, address _sender ) private returns (uint256 _pid) { _pid = productIds.current(); products[_pid] = Product({ startTime: block.timestamp, priceInUSD: _value, // price in USD durPlan: _durPlan, policyId: _policyId }); _setProductOwner(_pid, _sender); _increaseBalance(_sender); _buyProduct(_sender, _pid); productIds.increment(); } function getSignedMsgHash( string memory _policyId, uint256 _value, uint256 _durPlan ) internal pure returns (bytes32) { bytes32 msgHash = keccak256(abi.encodePacked(_policyId, _value, _durPlan)); /* Signature is produced by signing a keccak256 hash with the following format: "\x19Ethereum Signed Message\n" + len(msg) + msg */ return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash)); } }
buyProductETH function: this function should be called from user directly/
function buyProductByETH( string memory _policyId, uint256 _durPlan, bytes memory sig ) external payable nonReentrant whenNotPaused { bytes32 digest = getSignedMsgHash(_policyId, _value, _durPlan); permit(signer, digest, sig); uint256 tokenAmount = IExchangeAgent(exchangeAgent).getETHAmountForUSDC(_value); require(msg.value >= tokenAmount, "Insufficient amount"); if (msg.value > tokenAmount) { TransferHelper.safeTransferETH(msgSender(), msg.value - tokenAmount); } TransferHelper.safeTransferETH(devWallet, tokenAmount); uint256 _pid = buyProduct(uint128(_value), uint128(_durPlan), _policyId, msgSender()); emit BuyP4L(_pid, msgSender(), WETH, tokenAmount, _value); }
2,335,242
//Address: 0xdbfebf00f4601c176bdb61bf65f2abc9e213e065 //Contract name: EOSclassic //Balance: 0 Ether //Verification Date: 6/3/2018 //Transacion Count: 15 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title EOSclassic */ // Imports /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 */ 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); emit 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; emit 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); emit 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { // solium-disable-next-line security/no-send assert(owner.send(address(this).balance)); } } // Contract to help import the original EOS Crowdsale public key contract EOSContractInterface { mapping (address => string) public keys; function balanceOf( address who ) constant returns (uint value); } // EOSclassic smart contract contract EOSclassic is StandardToken, HasNoEther { // Welcome to EOSclassic string public constant name = "EOSclassic"; string public constant symbol = "EOSC"; uint8 public constant decimals = 18; // Total amount minted uint public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint(decimals)); // Amount given to founders uint public constant foundersAllocation = 100000000 * (10 ** uint(decimals)); // Contract address of the original EOS contracts address public constant eosTokenAddress = 0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0; address public constant eosCrowdsaleAddress = 0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf; // Map EOS keys; if not empty it should be favored over the original crowdsale address mapping (address => string) public keys; // Keep track of EOS->EOSclassic claims mapping (address => bool) public eosClassicClaimed; // LogClaim is called any time an EOS crowdsale user claims their EOSclassic equivalent event LogClaim (address user, uint amount); // LogRegister is called any time a user registers a new EOS public key event LogRegister (address user, string key); // ************************************************************ // Constructor; mints all tokens, assigns founder's allocation // ************************************************************ constructor() public { // Define total supply totalSupply_ = TOTAL_SUPPLY; // Allocate total supply of tokens to smart contract for disbursement balances[address(this)] = TOTAL_SUPPLY; // Announce initial allocation emit Transfer(0x0, address(this), TOTAL_SUPPLY); // Transfer founder's allocation balances[address(this)] = balances[address(this)].sub(foundersAllocation); balances[msg.sender] = balances[msg.sender].add(foundersAllocation); // Announce founder's allocation emit Transfer(address(this), msg.sender, foundersAllocation); } // Function that checks the original EOS token for a balance function queryEOSTokenBalance(address _address) view public returns (uint) { //return ERC20Basic(eosCrowdsaleAddress).balanceOf(_address); EOSContractInterface eosTokenContract = EOSContractInterface(eosTokenAddress); return eosTokenContract.balanceOf(_address); } // Function that returns any registered EOS address from the original EOS crowdsale function queryEOSCrowdsaleKey(address _address) view public returns (string) { EOSContractInterface eosCrowdsaleContract = EOSContractInterface(eosCrowdsaleAddress); return eosCrowdsaleContract.keys(_address); } // Use to claim EOS Classic from the calling address function claimEOSclassic() external returns (bool) { return claimEOSclassicFor(msg.sender); } // Use to claim EOSclassic for any Ethereum address function claimEOSclassicFor(address _toAddress) public returns (bool) { // Ensure that an address has been passed require (_toAddress != address(0)); // Ensure this address has not already been claimed require (isClaimed(_toAddress) == false); // Query the original EOS Crowdsale for address balance uint _eosContractBalance = queryEOSTokenBalance(_toAddress); // Ensure that address had some balance in the crowdsale require (_eosContractBalance > 0); // Sanity check: ensure we have enough tokens to send require (_eosContractBalance <= balances[address(this)]); // Mark address as claimed eosClassicClaimed[_toAddress] = true; // Convert equivalent amount of EOS to EOSclassic // Transfer EOS Classic tokens from this contract to claiming address balances[address(this)] = balances[address(this)].sub(_eosContractBalance); balances[_toAddress] = balances[_toAddress].add(_eosContractBalance); // Broadcast transfer emit Transfer(address(this), _toAddress, _eosContractBalance); // Broadcast claim emit LogClaim(_toAddress, _eosContractBalance); // Success! return true; } // Check any address to see if its EOSclassic has already been claimed function isClaimed(address _address) public view returns (bool) { return eosClassicClaimed[_address]; } // Returns the latest EOS key registered. // EOS token holders that never registered their EOS public key // can do so using the 'register' function in EOSclassic and then request restitution // via the EOS mainnet arbitration process. // EOS holders that previously registered can update their keys here; // This contract could be used in future key snapshots for future EOS forks. function getMyEOSKey() external view returns (string) { return getEOSKeyFor(msg.sender); } // Return the registered EOS public key for the passed address function getEOSKeyFor(address _address) public view returns (string) { string memory _eosKey; // Get any key registered with EOSclassic _eosKey = keys[_address]; if (bytes(_eosKey).length > 0) { // EOSclassic key was registered; return this over the original crowdsale address return _eosKey; } else { // EOSclassic doesn't have an EOS public key registered; return any original crowdsale key _eosKey = queryEOSCrowdsaleKey(_address); return _eosKey; } } // EOSclassic developer's note: the registration function is identical // to the original EOS crowdsale registration function with only the // freeze function removed, and 'emit' added to the LogRegister event, // per updated Solidity standards. // // Value should be a public key. Read full key import policy. // Manually registering requires a base58 // encoded using the STEEM, BTS, or EOS public key format. function register(string key) public { assert(bytes(key).length <= 64); keys[msg.sender] = key; emit LogRegister(msg.sender, key); } }
Check any address to see if its EOSclassic has already been claimed
function isClaimed(address _address) public view returns (bool) { return eosClassicClaimed[_address]; }
5,363,737
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. library SafeMath { function ADD750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "add: +"); return c; } function ADD750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, errorMessage); return c; } function SUB186(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB186(a, b, "sub: -"); } function SUB186(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL249(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING // 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 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; } function MUL249(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // 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 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function DIV270(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV270(a, b, "div: /"); } function DIV270(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD552(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return MOD552(a, b, "mod: %"); } function MOD552(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _not_entered410 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered581 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered410; } modifier NONREENTRANT577() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered581, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered581; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered410; } } interface IERC20 { function TOTALSUPPLY402() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF653(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER134(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE619(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE305(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM0(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER881(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL173(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library Address { function ISCONTRACT661(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function TOPAYABLE190(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE489(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER297(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.TRANSFER134.selector, to, value)); } function SAFETRANSFERFROM429(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.TRANSFERFROM0.selector, from, to, value)); } function SAFEAPPROVE484(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE619(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, value)); } function SAFEINCREASEALLOWANCE405(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE619(address(this), spender).ADD750(value); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE743(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE619(address(this), spender).SUB186(value, "SafeERC20: < 0"); CALLOPTIONALRETURN600(token, abi.encodeWithSelector(token.APPROVE305.selector, spender, newAllowance)); } function CALLOPTIONALRETURN600(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT661(), "SafeERC20: !contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: !succeed"); } } } library KperNetworkLibrary { function GETRESERVE107(address pair, address reserve) external view returns (uint) { //inject NONSTANDARD NAMING (uint _r0, uint _r1,) = IUniswapV2Pair(pair).GETRESERVES90(); if (IUniswapV2Pair(pair).TOKEN0518() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).TOKEN1343() == reserve) { return _r1; } else { return 0; } } } interface IUniswapV2Pair { event APPROVAL173(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER881(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME679() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL555() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS187() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY402() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF653(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE619(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE305(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER134(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM0(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR360() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH617() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES5(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT744(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT880(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN642(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP530( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY128() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY30() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0518() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1343() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES90() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST484() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST567() external view returns (uint); //inject NONSTANDARD NAMING function KLAST695() external view returns (uint); //inject NONSTANDARD NAMING function MINT553(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN246(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP955(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM112(address to) external; //inject NONSTANDARD NAMING function SYNC19() external; //inject NONSTANDARD NAMING function INITIALIZE501(address, address) external; //inject NONSTANDARD NAMING } interface IGovernance { function PROPOSEJOB67(address job) external; //inject NONSTANDARD NAMING } interface IKperNetworkHelper { function GETQUOTELIMIT193(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } contract KperNetwork is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; IKperNetworkHelper public KPRH; string public constant name59 = "Kper.Network"; //inject NONSTANDARD NAMING string public constant symbol586 = "KPER"; //inject NONSTANDARD NAMING uint8 public constant decimals310 = 18; //inject NONSTANDARD NAMING uint public totalSupply = 0; // Initial 0 mapping (address => address) public delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; bytes32 public constant domain_typehash648 = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); //inject NONSTANDARD NAMING bytes32 public immutable DOMAINSEPARATOR; bytes32 public constant delegation_typehash691 = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); //inject NONSTANDARD NAMING bytes32 public constant permit_typehash982 = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); //inject NONSTANDARD NAMING mapping (address => uint) public nonces; event DELEGATECHANGED7(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); //inject NONSTANDARD NAMING event DELEGATEVOTESCHANGED30(address indexed delegate, uint previousBalance, uint newBalance); //inject NONSTANDARD NAMING struct Checkpoint { uint32 fromBlock; uint votes; } function DELEGATE839(address delegatee) public { //inject NONSTANDARD NAMING _DELEGATE446(msg.sender, delegatee); } function DELEGATEBYSIG540(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(delegation_typehash691, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _DELEGATE446(signatory, delegatee); } function GETCURRENTVOTES464(address account) external view returns (uint) { //inject NONSTANDARD NAMING uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function GETPRIORVOTES822(address account, uint blockNumber) public view returns (uint) { //inject NONSTANDARD NAMING require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _DELEGATE446(address delegator, address delegatee) internal { //inject NONSTANDARD NAMING address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].ADD750(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DELEGATECHANGED7(delegator, currentDelegate, delegatee); _MOVEDELEGATES153(currentDelegate, delegatee, delegatorBalance); } function _MOVEDELEGATES153(address srcRep, address dstRep, uint amount) internal { //inject NONSTANDARD NAMING if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.SUB186(amount, "_moveVotes: underflows"); _WRITECHECKPOINT898(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.ADD750(amount); _WRITECHECKPOINT898(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _WRITECHECKPOINT898(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { //inject NONSTANDARD NAMING uint32 blockNumber = SAFE32446(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DELEGATEVOTESCHANGED30(delegatee, oldVotes, newVotes); } function SAFE32446(uint n, string memory errorMessage) internal pure returns (uint32) { //inject NONSTANDARD NAMING require(n < 2**32, errorMessage); return uint32(n); } event TRANSFER881(address indexed from, address indexed to, uint amount); //inject NONSTANDARD NAMING event APPROVAL173(address indexed owner, address indexed spender, uint amount); //inject NONSTANDARD NAMING event SUBMITJOB626(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event APPLYCREDIT477(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event REMOVEJOB82(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event UNBONDJOB739(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); //inject NONSTANDARD NAMING event JOBADDED910(address indexed job, uint block, address governance); //inject NONSTANDARD NAMING event JOBREMOVED937(address indexed job, uint block, address governance); //inject NONSTANDARD NAMING event KEEPERWORKED480(address indexed credit, address indexed job, address indexed keeper, uint block, uint amount); //inject NONSTANDARD NAMING event KEEPERBONDING674(address indexed keeper, uint block, uint active, uint bond); //inject NONSTANDARD NAMING event KEEPERBONDED647(address indexed keeper, uint block, uint activated, uint bond); //inject NONSTANDARD NAMING event KEEPERUNBONDING556(address indexed keeper, uint block, uint deactive, uint bond); //inject NONSTANDARD NAMING event KEEPERUNBOUND602(address indexed keeper, uint block, uint deactivated, uint bond); //inject NONSTANDARD NAMING event KEEPERSLASHED412(address indexed keeper, address indexed slasher, uint block, uint slash); //inject NONSTANDARD NAMING event KEEPERDISPUTE615(address indexed keeper, uint block); //inject NONSTANDARD NAMING event KEEPERRESOLVED375(address indexed keeper, uint block); //inject NONSTANDARD NAMING event ADDCREDIT188(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); //inject NONSTANDARD NAMING uint constant public bond875 = 3 days; //inject NONSTANDARD NAMING uint constant public unbond293 = 14 days; //inject NONSTANDARD NAMING uint constant public liquiditybond59 = 3 days; //inject NONSTANDARD NAMING uint constant public fee898 = 30; //inject NONSTANDARD NAMING uint constant public base419 = 10000; //inject NONSTANDARD NAMING address constant public eth194 = address(0xE); //inject NONSTANDARD NAMING mapping(address => mapping(address => uint)) public bondings; mapping(address => mapping(address => uint)) public unbondings; mapping(address => mapping(address => uint)) public partialUnbonding; mapping(address => mapping(address => uint)) public pendingbonds; mapping(address => mapping(address => uint)) public bonds; mapping(address => uint) public votes; uint public totalBonded = 0; mapping(address => uint) public firstSeen; mapping(address => bool) public disputes; mapping(address => uint) public lastJob; mapping(address => uint) public workCompleted; mapping(address => bool) public jobs; mapping(address => mapping(address => uint)) public credits; mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; mapping(address => uint) public jobProposalDelay; mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; mapping(address => bool) public keepers; mapping(address => bool) public blacklist; address[] public keeperList; address[] public jobList; address public governance; address public pendingGovernance; mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor(address _kph) public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash648, keccak256(bytes(name59)), _GETCHAINID109(), address(this))); KPRH = IKperNetworkHelper(_kph); } function ADDCREDITETH565(address job) external payable { //inject NONSTANDARD NAMING require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.MUL249(fee898).DIV270(base419); credits[job][eth194] = credits[job][eth194].ADD750(msg.value.SUB186(_fee)); payable(governance).transfer(_fee); emit ADDCREDIT188(eth194, job, msg.sender, block.number, msg.value); } function ADDCREDIT18(address credit, address job, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).BALANCEOF653(address(this)); IERC20(credit).SAFETRANSFERFROM429(msg.sender, address(this), amount); uint _received = IERC20(credit).BALANCEOF653(address(this)).SUB186(_before); uint _fee = _received.MUL249(fee898).DIV270(base419); credits[job][credit] = credits[job][credit].ADD750(_received.SUB186(_fee)); IERC20(credit).SAFETRANSFER297(governance, _fee); emit ADDCREDIT188(credit, job, msg.sender, block.number, _received); } function ADDVOTES465(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addVotes: !gov"); _ACTIVATE236(voter, address(this)); votes[voter] = votes[voter].ADD750(amount); totalBonded = totalBonded.ADD750(amount); _MOVEDELEGATES153(address(0), delegates[voter], amount); } function REMOVEVOTES245(address voter, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].SUB186(amount); totalBonded = totalBonded.SUB186(amount); _MOVEDELEGATES153(delegates[voter], address(0), amount); } function ADDKPRCREDIT8(address job, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addKPRCredit: !gov"); require(jobs[job], "addKPRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].ADD750(amount); _MINT726(address(this), amount); emit ADDCREDIT188(address(this), job, msg.sender, block.number, amount); } function APPROVELIQUIDITY363(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "approveLiquidity: !gov"); require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } function REVOKELIQUIDITY704(address liquidity) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "revokeLiquidity: !gov"); liquidityAccepted[liquidity] = false; } function PAIRS99() external view returns (address[] memory) { //inject NONSTANDARD NAMING return liquidityPairs; } function ADDLIQUIDITYTOJOB689(address liquidity, address job, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).SAFETRANSFERFROM429(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].ADD750(amount); liquidityApplied[msg.sender][liquidity][job] = now.ADD750(liquiditybond59); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].ADD750(amount); if (!jobs[job] && jobProposalDelay[job] < now) { IGovernance(governance).PROPOSEJOB67(job); jobProposalDelay[job] = now.ADD750(unbond293); } emit SUBMITJOB626(job, liquidity, msg.sender, block.number, amount); } function APPLYCREDITTOJOB508(address provider, address liquidity, address job) external { //inject NONSTANDARD NAMING require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = KperNetworkLibrary.GETRESERVE107(liquidity, address(this)); uint _credit = _liquidity.MUL249(liquidityAmount[provider][liquidity][job]).DIV270(IERC20(liquidity).TOTALSUPPLY402()); _MINT726(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].ADD750(_credit); liquidityAmount[provider][liquidity][job] = 0; emit APPLYCREDIT477(job, liquidity, provider, block.number, _credit); } function UNBONDLIQUIDITYFROMJOB746(address liquidity, address job, uint amount) external { //inject NONSTANDARD NAMING require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.ADD750(unbond293); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].ADD750(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = KperNetworkLibrary.GETRESERVE107(liquidity, address(this)); uint _credit = _liquidity.MUL249(amount).DIV270(IERC20(liquidity).TOTALSUPPLY402()); if (_credit > credits[job][address(this)]) { _BURN941(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _BURN941(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].SUB186(_credit); } emit UNBONDJOB739(job, liquidity, msg.sender, block.number, amount); } function REMOVELIQUIDITYFROMJOB500(address liquidity, address job) external { //inject NONSTANDARD NAMING require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].SUB186(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).SAFETRANSFER297(msg.sender, _amount); emit REMOVEJOB82(job, liquidity, msg.sender, block.number, _amount); } function MINT553(uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "mint: !gov"); _MINT726(governance, amount); } function BURN246(uint amount) external { //inject NONSTANDARD NAMING _BURN941(msg.sender, amount); } function _MINT726(address dst, uint amount) internal { //inject NONSTANDARD NAMING // mint the amount totalSupply = totalSupply.ADD750(amount); // transfer the amount to the recipient balances[dst] = balances[dst].ADD750(amount); emit TRANSFER881(address(0), dst, amount); } function _BURN941(address dst, uint amount) internal { //inject NONSTANDARD NAMING require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].SUB186(amount, "_burn: exceeds balance"); totalSupply = totalSupply.SUB186(amount); emit TRANSFER881(dst, address(0), amount); } function WORKED503(address keeper) external { //inject NONSTANDARD NAMING WORKRECEIPT237(keeper, KPRH.GETQUOTELIMIT193(_gasUsed.SUB186(gasleft()))); } function WORKRECEIPT237(address keeper, uint amount) public { //inject NONSTANDARD NAMING require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.GETQUOTELIMIT193(_gasUsed.SUB186(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; _REWARD950(keeper, amount); workCompleted[keeper] = workCompleted[keeper].ADD750(amount); emit KEEPERWORKED480(address(this), msg.sender, keeper, block.number, amount); } function RECEIPT523(address credit, address keeper, uint amount) external { //inject NONSTANDARD NAMING require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; IERC20(credit).SAFETRANSFER297(keeper, amount); emit KEEPERWORKED480(credit, msg.sender, keeper, block.number, amount); } function RECEIPTETH18(address keeper, uint amount) external { //inject NONSTANDARD NAMING require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][eth194] = credits[msg.sender][eth194].SUB186(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KEEPERWORKED480(eth194, msg.sender, keeper, block.number, amount); } function _REWARD950(address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][address(this)] = bonds[_from][address(this)].ADD750(_amount); totalBonded = totalBonded.ADD750(_amount); _MOVEDELEGATES153(address(0), delegates[_from], _amount); emit TRANSFER881(msg.sender, _from, _amount); } function _BOND529(address bonding, address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][bonding] = bonds[_from][bonding].ADD750(_amount); if (bonding == address(this)) { totalBonded = totalBonded.ADD750(_amount); _MOVEDELEGATES153(address(0), delegates[_from], _amount); } } function _UNBOND647(address bonding, address _from, uint _amount) internal { //inject NONSTANDARD NAMING bonds[_from][bonding] = bonds[_from][bonding].SUB186(_amount); if (bonding == address(this)) { totalBonded = totalBonded.SUB186(_amount); _MOVEDELEGATES153(delegates[_from], address(0), _amount); } } function ADDJOB840(address job) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "addJob: !gov"); require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JOBADDED910(job, block.number, msg.sender); } function GETJOBS254() external view returns (address[] memory) { //inject NONSTANDARD NAMING return jobList; } function REMOVEJOB380(address job) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "removeJob: !gov"); jobs[job] = false; emit JOBREMOVED937(job, block.number, msg.sender); } function SETKPERNETWORKHELPER865(IKperNetworkHelper _kprh) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setKperNetworkHelper: !gov"); KPRH = _kprh; } function SETGOVERNANCE939(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE630() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } function ISKEEPER927(address keeper) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper]; } function ISMINKEEPER163(address keeper, uint minBond, uint earned, uint age) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].ADD750(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.SUB186(firstSeen[keeper]) >= age; } function ISBONDEDKEEPER241(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { //inject NONSTANDARD NAMING _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.SUB186(firstSeen[keeper]) >= age; } function BOND260(address bonding, uint amount) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.ADD750(bond875); if (bonding == address(this)) { _TRANSFERTOKENS224(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).BALANCEOF653(address(this)); IERC20(bonding).SAFETRANSFERFROM429(msg.sender, address(this), amount); amount = IERC20(bonding).BALANCEOF653(address(this)).SUB186(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].ADD750(amount); emit KEEPERBONDING674(msg.sender, block.number, bondings[msg.sender][bonding], amount); } function GETKEEPERS116() external view returns (address[] memory) { //inject NONSTANDARD NAMING return keeperList; } function ACTIVATE41(address bonding) external { //inject NONSTANDARD NAMING require(!blacklist[msg.sender], "activate: blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding"); _ACTIVATE236(msg.sender, bonding); } function _ACTIVATE236(address keeper, address bonding) internal { //inject NONSTANDARD NAMING if (firstSeen[keeper] == 0) { firstSeen[keeper] = now; keeperList.push(keeper); lastJob[keeper] = now; } keepers[keeper] = true; _BOND529(bonding, keeper, pendingbonds[keeper][bonding]); pendingbonds[keeper][bonding] = 0; emit KEEPERBONDED647(keeper, block.number, block.timestamp, bonds[keeper][bonding]); } function UNBOND442(address bonding, uint amount) external { //inject NONSTANDARD NAMING unbondings[msg.sender][bonding] = now.ADD750(unbond293); _UNBOND647(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].ADD750(amount); emit KEEPERUNBONDING556(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } function WITHDRAW592(address bonding) external NONREENTRANT577 { //inject NONSTANDARD NAMING require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _TRANSFERTOKENS224(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).SAFETRANSFER297(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KEEPERUNBOUND602(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } function DISPUTE590(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "dispute: !gov"); disputes[keeper] = true; emit KEEPERDISPUTE615(keeper, block.number); } function SLASH39(address bonded, address keeper, uint amount) public NONREENTRANT577 { //inject NONSTANDARD NAMING require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _TRANSFERTOKENS224(address(this), governance, amount); } else { IERC20(bonded).SAFETRANSFER297(governance, amount); } _UNBOND647(bonded, keeper, amount); disputes[keeper] = false; emit KEEPERSLASHED412(keeper, msg.sender, block.number, amount); } function REVOKE253(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "slash: !gov"); keepers[keeper] = false; blacklist[keeper] = true; SLASH39(address(this), keeper, bonds[keeper][address(this)]); } function RESOLVE476(address keeper) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "resolve: !gov"); disputes[keeper] = false; emit KEEPERRESOLVED375(keeper, block.number); } function ALLOWANCE619(address account, address spender) external view returns (uint) { //inject NONSTANDARD NAMING return allowances[account][spender]; } function APPROVE305(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING allowances[msg.sender][spender] = amount; emit APPROVAL173(msg.sender, spender, amount); return true; } function PERMIT744(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { //inject NONSTANDARD NAMING bytes32 structHash = keccak256(abi.encode(permit_typehash982, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit APPROVAL173(owner, spender, amount); } function BALANCEOF653(address account) external view returns (uint) { //inject NONSTANDARD NAMING return balances[account]; } function TRANSFER134(address dst, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFERTOKENS224(msg.sender, dst, amount); return true; } function TRANSFERFROM0(address src, address dst, uint amount) external returns (bool) { //inject NONSTANDARD NAMING address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.SUB186(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit APPROVAL173(src, spender, newAllowance); } _TRANSFERTOKENS224(src, dst, amount); return true; } function _TRANSFERTOKENS224(address src, address dst, uint amount) internal { //inject NONSTANDARD NAMING require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].SUB186(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].ADD750(amount, "_transferTokens: overflows"); emit TRANSFER881(src, dst, amount); } function _GETCHAINID109() internal pure returns (uint) { //inject NONSTANDARD NAMING uint chainId; assembly { chainId := chainid() } return chainId; } }
inject NONSTANDARD NAMING
function APPLYCREDITTOJOB508(address provider, address liquidity, address job) external {
12,787,907
./full_match/1/0x5E4E6685a84eb1A597c7F794700893ab8FfD04f4/sources/contracts/DevFund.sol
View remaining reward for an address. forAddress holder's address./
function rewardFor(address forAddress) public view returns (uint256) { uint256 _currentBalance = rewardToken.balanceOf(address(this)); uint256 _totalReward = totalReward + (_currentBalance > prevBalance ? _currentBalance - prevBalance : 0); return owed[forAddress] + (holderToken.balanceOf(forAddress) * (_totalReward - rewardAtTimeOfWithdraw[forAddress])) / holderToken.totalSupply(); }
3,846,795
// SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "../IAdapter.sol"; import "../../lib/aavee/Aavee.sol"; import "../../lib/chai/ChaiExchange.sol"; import "../../lib/bprotocol/BProtocolAMM.sol"; import "../../lib/bzx/BZX.sol"; import "../../lib/smoothy/SmoothyV1.sol"; import "../../lib/uniswap/UniswapV1.sol"; import "../../lib/kyberdmm/KyberDmm.sol"; import "../../lib/jarvis/Jarvis.sol"; import "../../lib/lido/Lido.sol"; import "../../lib/makerpsm/MakerPsm.sol"; /** * @dev This contract will route call to: * 0- ChaiExchange * 1- UniswapV1 * 2- SmoothyV1 * 3- BZX * 4- BProtocol * 5- Aave * 6- KyberDMM * 7- Jarvis * 8 - Lido * 9 - MakerPsm * The above are the indexes */ contract Adapter03 is IAdapter, ChaiExchange, UniswapV1, SmoothyV1, BZX, BProtocol, Aavee, KyberDmm, Jarvis, Lido, MakerPsm { using SafeMath for uint256; /*solhint-disable no-empty-blocks*/ constructor( uint16 aaveeRefCode, address aaveeSpender, address uniswapFactory, address chai, address dai, address weth, address stETH ) public WethProvider(weth) Aavee(aaveeRefCode, aaveeSpender) UniswapV1(uniswapFactory) ChaiExchange(chai, dai) Lido(stETH) MakerPsm(dai) {} /*solhint-enable no-empty-blocks*/ function initialize(bytes calldata) external override { revert("METHOD NOT IMPLEMENTED"); } function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256, Utils.Route[] calldata route ) external payable override { for (uint256 i = 0; i < route.length; i++) { if (route[i].index == 0) { //swap on ChaiExchange swapOnChai(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000)); } else if (route[i].index == 1) { //swap on Uniswap swapOnUniswapV1(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000)); } else if (route[i].index == 2) { //swap on Smoothy swapOnSmoothyV1( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 3) { //swap on BZX swapOnBzx(fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].payload); } else if (route[i].index == 4) { //swap on BProtocol swapOnBProtocol( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 5) { //swap on aavee swapOnAavee( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 6) { //swap on KyberDmm swapOnKyberDmm( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 7) { //swap on Jarvis swapOnJarvis( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 8) { //swap on Lido swapOnLido( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else if (route[i].index == 9) { //swap on MakerPsm swapOnMakerPsm( fromToken, toToken, fromAmount.mul(route[i].percent).div(10000), route[i].targetExchange, route[i].payload ); } else { revert("Index not supported"); } } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "../lib/Utils.sol"; interface IAdapter { /** * @dev Certain adapters needs to be initialized. * This method will be called from Augustus */ function initialize(bytes calldata data) external; /** * @dev The function which performs the swap on an exchange. * @param fromToken Address of the source token * @param toToken Address of the destination token * @param fromAmount Amount of source tokens to be swapped * @param networkFee NOT USED - Network fee to be used in this router * @param route Route to be followed */ function swap( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 networkFee, Utils.Route[] calldata route ) external payable; } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IAavee.sol"; import "../Utils.sol"; contract Aavee { struct AaveeDataV1 { address aToken; } uint16 public immutable refCodeV1; address public immutable spender; constructor(uint16 _refCode, address _spender) public { refCodeV1 = _refCode; spender = _spender; } function swapOnAavee( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { _swapOnAavee(fromToken, toToken, fromAmount, exchange, payload); } function buyOnAavee( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { _swapOnAavee(fromToken, toToken, fromAmount, exchange, payload); } function _swapOnAavee( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes memory payload ) private { AaveeDataV1 memory data = abi.decode(payload, (AaveeDataV1)); Utils.approve(spender, address(fromToken), fromAmount); if (address(fromToken) == address(data.aToken)) { require(IAaveToken(data.aToken).underlyingAssetAddress() == address(toToken), "Invalid to token"); IAaveToken(data.aToken).redeem(fromAmount); } else if (address(toToken) == address(data.aToken)) { require(IAaveToken(data.aToken).underlyingAssetAddress() == address(fromToken), "Invalid to token"); if (address(fromToken) == Utils.ethAddress()) { IAaveV1LendingPool(exchange).deposit{ value: fromAmount }(fromToken, fromAmount, refCodeV1); } else { IAaveV1LendingPool(exchange).deposit(fromToken, fromAmount, refCodeV1); } } else { revert("Invalid aToken"); } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IChai.sol"; import "../Utils.sol"; contract ChaiExchange { address public immutable chai; address public immutable dai; constructor(address _chai, address _dai) public { chai = _chai; dai = _dai; } function swapOnChai( IERC20 fromToken, IERC20 toToken, uint256 fromAmount ) internal { _swapOnChai(fromToken, toToken, fromAmount); } function buyOnChai( IERC20 fromToken, IERC20 toToken, uint256 fromAmount ) internal { _swapOnChai(fromToken, toToken, fromAmount); } function _swapOnChai( IERC20 fromToken, IERC20 toToken, uint256 fromAmount ) private { Utils.approve(address(chai), address(fromToken), fromAmount); if (address(fromToken) == chai) { require(address(toToken) == dai, "Destination token should be dai"); IChai(chai).exit(address(this), fromAmount); } else if (address(fromToken) == dai) { require(address(toToken) == chai, "Destination token should be chai"); IChai(chai).join(address(this), fromAmount); } else { revert("Invalid fromToken"); } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; import "./IBProtocolAMM.sol"; contract BProtocol { function swapOnBProtocol( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { Utils.approve(address(exchange), address(fromToken), fromAmount); IBProtocolAMM(exchange).swap(fromAmount, 1, payable(address(this))); } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "./IBZX.sol"; import "../Utils.sol"; import "../WethProvider.sol"; abstract contract BZX is WethProvider { struct BZXData { address iToken; } function swapOnBzx( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, bytes calldata payload ) internal { _swapOnBZX(fromToken, toToken, fromAmount, payload); } function buyOnBzx( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, bytes calldata payload ) internal { _swapOnBZX(fromToken, toToken, fromAmount, payload); } function _swapOnBZX( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, bytes memory payload ) private { BZXData memory data = abi.decode(payload, (BZXData)); Utils.approve(address(data.iToken), address(fromToken), fromAmount); if (address(fromToken) == address(data.iToken)) { if (address(toToken) == Utils.ethAddress()) { require(IBZX(data.iToken).loanTokenAddress() == WETH, "Invalid to token"); IBZX(data.iToken).burnToEther(payable(address(this)), fromAmount); } else { require(IBZX(data.iToken).loanTokenAddress() == address(toToken), "Invalid to token"); IBZX(data.iToken).burn(address(this), fromAmount); } } else if (address(toToken) == address(data.iToken)) { if (address(fromToken) == Utils.ethAddress()) { require(IBZX(data.iToken).loanTokenAddress() == WETH, "Invalid from token"); IBZX(data.iToken).mintWithEther{ value: fromAmount }(address(this)); } else { require(IBZX(data.iToken).loanTokenAddress() == address(fromToken), "Invalid from token"); IBZX(data.iToken).mint(address(this), fromAmount); } } else { revert("Invalid token pair!!"); } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; import "./ISmoothyV1.sol"; import "../weth/IWETH.sol"; contract SmoothyV1 { struct SmoothyV1Data { uint256 i; uint256 j; } function swapOnSmoothyV1( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { SmoothyV1Data memory data = abi.decode(payload, (SmoothyV1Data)); Utils.approve(exchange, address(fromToken), fromAmount); ISmoothyV1(exchange).swap(data.i, data.j, fromAmount, 1); } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; import "./IUniswapExchange.sol"; import "./IUniswapFactory.sol"; contract UniswapV1 { using SafeMath for uint256; address public immutable factory; constructor(address _factory) public { factory = _factory; } function swapOnUniswapV1( IERC20 fromToken, IERC20 toToken, uint256 fromAmount ) internal { _swapOnUniswapV1(fromToken, toToken, fromAmount, 1); } function buyOnUniswapV1( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount ) internal { address exchange = getExchange(fromToken, toToken); Utils.approve(address(exchange), address(fromToken), fromAmount); if (address(fromToken) == Utils.ethAddress()) { IUniswapExchange(exchange).ethToTokenSwapOutput{ value: fromAmount }(toAmount, block.timestamp); } else if (address(toToken) == Utils.ethAddress()) { IUniswapExchange(exchange).tokenToEthSwapOutput(toAmount, fromAmount, block.timestamp); } else { IUniswapExchange(exchange).tokenToTokenSwapOutput( toAmount, fromAmount, Utils.maxUint(), block.timestamp, address(toToken) ); } } function getExchange(IERC20 fromToken, IERC20 toToken) private view returns (address) { address exchangeAddress = address(fromToken) == Utils.ethAddress() ? address(toToken) : address(fromToken); return IUniswapFactory(factory).getExchange(exchangeAddress); } function _swapOnUniswapV1( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount ) private returns (uint256) { address exchange = getExchange(fromToken, toToken); Utils.approve(exchange, address(fromToken), fromAmount); uint256 receivedAmount = 0; if (address(fromToken) == Utils.ethAddress()) { receivedAmount = IUniswapExchange(exchange).ethToTokenSwapInput{ value: fromAmount }( toAmount, block.timestamp ); } else if (address(toToken) == Utils.ethAddress()) { receivedAmount = IUniswapExchange(exchange).tokenToEthSwapInput(fromAmount, toAmount, block.timestamp); } else { receivedAmount = IUniswapExchange(exchange).tokenToTokenSwapInput( fromAmount, toAmount, 1, block.timestamp, address(toToken) ); } return receivedAmount; } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; import "../weth/IWETH.sol"; import "../WethProvider.sol"; import "./IKyberDmmRouter.sol"; abstract contract KyberDmm is WethProvider { uint256 constant MAX_INT = 115792089237316195423570985008687907853269984665640564039457584007913129639935; struct KyberDMMData { address[] poolPath; IERC20[] path; } function swapOnKyberDmm( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { KyberDMMData memory data = abi.decode(payload, (KyberDMMData)); address _fromToken = address(fromToken) == Utils.ethAddress() ? WETH : address(fromToken); address _toToken = address(toToken) == Utils.ethAddress() ? WETH : address(toToken); if (address(fromToken) == Utils.ethAddress()) { IWETH(WETH).deposit{ value: fromAmount }(); } Utils.approve(address(exchange), _fromToken, fromAmount); IDMMExchangeRouter(exchange).swapExactTokensForTokens( fromAmount, 1, data.poolPath, data.path, address(this), MAX_INT // deadline ); if (address(toToken) == Utils.ethAddress()) { IWETH(WETH).withdraw(IERC20(WETH).balanceOf(address(this))); } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; interface IJarvisPool { struct MintParams { // Derivative to use address derivative; // Minimum amount of synthetic tokens that a user wants to mint using collateral (anti-slippage) uint256 minNumTokens; // Amount of collateral that a user wants to spend for minting uint256 collateralAmount; // Maximum amount of fees in percentage that user is willing to pay uint256 feePercentage; // Expiration time of the transaction uint256 expiration; // Address to which send synthetic tokens minted address recipient; } struct RedeemParams { // Derivative to use address derivative; // Amount of synthetic tokens that user wants to use for redeeming uint256 numTokens; // Minimium amount of collateral that user wants to redeem (anti-slippage) uint256 minCollateral; // Maximum amount of fees in percentage that user is willing to pay uint256 feePercentage; // Expiration time of the transaction uint256 expiration; // Address to which send collateral tokens redeemed address recipient; } struct ExchangeParams { // Derivative of source pool address derivative; // Destination pool address destPool; // Derivative of destination pool address destDerivative; // Amount of source synthetic tokens that user wants to use for exchanging uint256 numTokens; // Minimum Amount of destination synthetic tokens that user wants to receive (anti-slippage) uint256 minDestNumTokens; // Maximum amount of fees in percentage that user is willing to pay uint256 feePercentage; // Expiration time of the transaction uint256 expiration; // Address to which send synthetic tokens exchanged address recipient; } function mint(MintParams memory mintParams) external returns (uint256 syntheticTokensMinted, uint256 feePaid); function redeem(RedeemParams memory redeemParams) external returns (uint256 collateralRedeemed, uint256 feePaid); function exchange(ExchangeParams memory exchangeParams) external returns (uint256 destNumTokensMinted, uint256 feePaid); } contract Jarvis { enum MethodType { mint, redeem, exchange } struct JarvisData { uint256 opType; address derivatives; address destDerivatives; uint128 fee; address destPool; uint128 expiration; } function swapOnJarvis( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { JarvisData memory data = abi.decode(payload, (JarvisData)); Utils.approve(exchange, address(fromToken), fromAmount); if (data.opType == uint256(MethodType.mint)) { IJarvisPool.MintParams memory mintParam = IJarvisPool.MintParams( data.derivatives, 1, fromAmount, data.fee, data.expiration, address(this) ); IJarvisPool(exchange).mint(mintParam); } else if (data.opType == uint256(MethodType.redeem)) { IJarvisPool.RedeemParams memory redeemParam = IJarvisPool.RedeemParams( data.derivatives, fromAmount, 1, data.fee, data.expiration, address(this) ); IJarvisPool(exchange).redeem(redeemParam); } else if (data.opType == uint256(MethodType.exchange)) { IJarvisPool.ExchangeParams memory exchangeParam = IJarvisPool.ExchangeParams( data.derivatives, data.destPool, data.destDerivatives, fromAmount, 1, data.fee, data.expiration, address(this) ); IJarvisPool(exchange).exchange(exchangeParam); } else { revert("Invalid opType"); } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../Utils.sol"; import "./IstETH.sol"; contract Lido { address public immutable stETH; constructor(address _stETH) public { stETH = _stETH; } function swapOnLido( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { require(address(fromToken) == Utils.ethAddress(), "srcToken should be ETH"); require(address(toToken) == stETH, "destToken should be stETH"); IstETH(stETH).submit{ value: fromAmount }(address(0)); } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IPsm.sol"; import "../Utils.sol"; contract MakerPsm { using SafeMath for uint256; address immutable daiMaker; // dai name has collision with chai uint256 constant WAD = 1e18; struct MakerPsmData { address gemJoinAddress; uint256 toll; uint256 to18ConversionFactor; } constructor(address _dai) public { daiMaker = _dai; } function swapOnMakerPsm( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, address exchange, bytes calldata payload ) internal { MakerPsmData memory makerPsmData = abi.decode(payload, (MakerPsmData)); if (address(fromToken) == daiMaker) { uint256 gemAmt = fromAmount.mul(WAD).div(WAD.add(makerPsmData.toll).mul(makerPsmData.to18ConversionFactor)); Utils.approve(exchange, address(fromToken), fromAmount); IPsm(exchange).buyGem(address(this), gemAmt); } else { Utils.approve(makerPsmData.gemJoinAddress, address(fromToken), fromAmount); IPsm(exchange).sellGem(address(this), fromAmount); } } function buyOnMakerPsm( IERC20 fromToken, IERC20 toToken, uint256 fromAmount, uint256 toAmount, address exchange, bytes calldata payload ) internal { MakerPsmData memory makerPsmData = abi.decode(payload, (MakerPsmData)); if (address(fromToken) == daiMaker) { Utils.approve(exchange, address(fromToken), fromAmount); IPsm(exchange).buyGem(address(this), toAmount); } else { uint256 a = toAmount.mul(WAD); uint256 b = WAD.sub(makerPsmData.toll).mul(makerPsmData.to18ConversionFactor); // ceil division to handle rounding error uint256 gemAmt = (a.add(b).sub(1)).div(b); Utils.approve(makerPsmData.gemJoinAddress, address(fromToken), fromAmount); IPsm(exchange).sellGem(address(this), gemAmt); } } } /*solhint-disable avoid-low-level-calls */ // SPDX-License-Identifier: ISC pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../ITokenTransferProxy.sol"; interface IERC20Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } interface IERC20PermitLegacy { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } library Utils { using SafeMath for uint256; using SafeERC20 for IERC20; address private constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); uint256 private constant MAX_UINT = type(uint256).max; /** * @param fromToken Address of the source token * @param fromAmount Amount of source tokens to be swapped * @param toAmount Minimum destination token amount expected out of this swap * @param expectedAmount Expected amount of destination tokens without slippage * @param beneficiary Beneficiary address * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100% * @param path Route to be taken for this swap to take place */ struct SellData { address fromToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address payable beneficiary; Utils.Path[] path; address payable partner; uint256 feePercent; bytes permit; uint256 deadline; bytes16 uuid; } struct BuyData { address adapter; address fromToken; address toToken; uint256 fromAmount; uint256 toAmount; address payable beneficiary; Utils.Route[] route; address payable partner; uint256 feePercent; bytes permit; uint256 deadline; bytes16 uuid; } struct MegaSwapSellData { address fromToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address payable beneficiary; Utils.MegaSwapPath[] path; address payable partner; uint256 feePercent; bytes permit; uint256 deadline; bytes16 uuid; } struct SimpleData { address fromToken; address toToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address[] callees; bytes exchangeData; uint256[] startIndexes; uint256[] values; address payable beneficiary; address payable partner; uint256 feePercent; bytes permit; uint256 deadline; bytes16 uuid; } struct Adapter { address payable adapter; uint256 percent; uint256 networkFee; //NOT USED Route[] route; } struct Route { uint256 index; //Adapter at which index needs to be used address targetExchange; uint256 percent; bytes payload; uint256 networkFee; //NOT USED - Network fee is associated with 0xv3 trades } struct MegaSwapPath { uint256 fromAmountPercent; Path[] path; } struct Path { address to; uint256 totalNetworkFee; //NOT USED - Network fee is associated with 0xv3 trades Adapter[] adapters; } function ethAddress() internal pure returns (address) { return ETH_ADDRESS; } function maxUint() internal pure returns (uint256) { return MAX_UINT; } function approve( address addressToApprove, address token, uint256 amount ) internal { if (token != ETH_ADDRESS) { IERC20 _token = IERC20(token); uint256 allowance = _token.allowance(address(this), addressToApprove); if (allowance < amount) { _token.safeApprove(addressToApprove, 0); _token.safeIncreaseAllowance(addressToApprove, MAX_UINT); } } } function transferTokens( address token, address payable destination, uint256 amount ) internal { if (amount > 0) { if (token == ETH_ADDRESS) { (bool result, ) = destination.call{ value: amount, gas: 10000 }(""); require(result, "Failed to transfer Ether"); } else { IERC20(token).safeTransfer(destination, amount); } } } function tokenBalance(address token, address account) internal view returns (uint256) { if (token == ETH_ADDRESS) { return account.balance; } else { return IERC20(token).balanceOf(account); } } function permit(address token, bytes memory permit) internal { if (permit.length == 32 * 7) { (bool success, ) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit)); require(success, "Permit failed"); } if (permit.length == 32 * 8) { (bool success, ) = token.call(abi.encodePacked(IERC20PermitLegacy.permit.selector, permit)); require(success, "Permit failed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface ITokenTransferProxy { function transferFrom( address token, address from, address to, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAaveToken { function redeem(uint256 amount) external; function underlyingAssetAddress() external view returns (address); } interface IAaveV1LendingPool { function deposit( IERC20 token, uint256 amount, uint16 refCode ) external payable; } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IChai { function join(address dst, uint256 wad) external; function exit(address src, uint256 wad) external; } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IBProtocolAMM { function swap( uint256 lusdAmount, uint256 minEthReturn, address payable dest ) external returns (uint256); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IBZX { function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount); function mintWithEther(address receiver) external payable returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function burnToEther(address payable receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function loanTokenAddress() external view returns (address); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; contract WethProvider { /*solhint-disable var-name-mixedcase*/ address public immutable WETH; /*solhint-enable var-name-mixedcase*/ constructor(address weth) public { WETH = weth; } } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface ISmoothyV1 { function swap( uint256 bTokenIdxIn, uint256 bTokenIdxOut, uint256 bTokenInAmount, uint256 bTokenOutMin ) external; } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; abstract contract IWETH is IERC20 { function deposit() external payable virtual; function withdraw(uint256 amount) external virtual; } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IUniswapExchange { function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) external payable returns (uint256 tokensBought); function ethToTokenSwapOutput(uint256 tokensBought, uint256 deadline) external payable returns (uint256 ethSold); function tokenToEthSwapInput( uint256 tokensSold, uint256 minEth, uint256 deadline ) external returns (uint256 ethBought); function tokenToEthSwapOutput( uint256 ethBought, uint256 maxTokens, uint256 deadline ) external returns (uint256 tokensSold); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddr ) external returns (uint256 tokensBought); function tokenToTokenSwapOutput( uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, address toToken ) external returns (uint256 tokensSold); function ethToTokenTransferInput( uint256 min_tokens, uint256 deadline, address recipient ) external payable returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external payable returns (uint256 eth_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient ) external returns (uint256 eth_bought); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external returns (uint256 tokens_sold); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external returns (uint256 tokens_bought); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external returns (uint256 tokens_sold); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "./IUniswapExchange.sol"; interface IUniswapFactory { function getExchange(address token) external view returns (address exchange); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDMMExchangeRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata poolsPath, IERC20[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata poolsPath, IERC20[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IstETH { function submit(address _referral) external payable returns (uint256); } // SPDX-License-Identifier: ISC pragma solidity 0.7.5; interface IPsm { function sellGem(address usr, uint256 gemAmt) external; function buyGem(address usr, uint256 gemAmt) external; }
solhint-enable no-empty-blocks/
function initialize(bytes calldata) external override { revert("METHOD NOT IMPLEMENTED"); }
11,825,399
/** *Submitted for verification at Etherscan.io on 2022-04-08 */ // SPDX-License-Identifier: MIT // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; contract HashBet is Ownable, ReentrancyGuard { // Modulo is the number of equiprobable outcomes in a game: // 2 for coin flip // 6 for dice roll // 6*6 = 36 for double dice // 37 for roulette // 100 for polyroll uint constant MAX_MODULO = 100; // Modulos below MAX_MASK_MODULO are checked against a bit mask, allowing betting on specific outcomes. // For example in a dice roll (modolo = 6), // 000001 mask means betting on 1. 000001 converted from binary to decimal becomes 1. // 101000 mask means betting on 4 and 6. 101000 converted from binary to decimal becomes 40. // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint constant MAX_MASK_MODULO = 40; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions dice2.win croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; // This is a check on bet mask overflow. Maximum mask is equivalent to number of possible binary outcomes for maximum modulo. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // These are constants taht make O(1) population count in placeBet possible. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; // Sum of all historical deposits and withdrawals. Used for calculating profitability. Profit = Balance - cumulativeDeposit + cumulativeWithdrawal uint public cumulativeDeposit; uint public cumulativeWithdrawal; // In addition to house edge, wealth tax is added every time the bet amount exceeds a multiple of a threshold. // For example, if wealthTaxIncrementThreshold = 3000 ether, // A bet amount of 3000 ether will have a wealth tax of 1% in addition to house edge. // A bet amount of 6000 ether will have a wealth tax of 2% in addition to house edge. uint public wealthTaxIncrementThreshold = 3000 ether; uint public wealthTaxIncrementPercent = 1; // The minimum and maximum bets. uint public minBetAmount = 0.01 ether; uint public maxBetAmount = 10000 ether; // max bet profit. Used to cap bets against dynamic odds. uint public maxProfit = 300000 ether; // Funds that are locked in potentially winning bets. Prevents contract from committing to new bets that it cannot pay out. uint public lockedInBets; // Info of each bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Block number of placeBet tx. uint placeBlockNumber; // Address of a gambler, used to pay out winning bets. address payable gambler; // Status of bet settlement. bool isSettled; // Outcome of bet. uint outcome; // Win amount. uint winAmount; // Random number used to settle bet. uint randomNumber; // Keccak256 hash of some secret "reveal" random number. uint commit; } // Each bet is deducted dynamic uint public houseEdgePercent = 1; // Mapping from commits to all currently active & processed bets. mapping (uint => Bet) bets; // Events event BetPlaced(address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask, uint commit); event BetSettled(address indexed gambler, uint amount, uint8 indexed modulo, uint8 rollUnder, uint40 mask, uint outcome, uint winAmount); event BetRefunded(address indexed gambler, uint amount); // Fallback payable function used to top up the bank roll. fallback() external payable { cumulativeDeposit += msg.value; } receive() external payable { cumulativeDeposit += msg.value; } // See ETH balance. function balance() external view returns (uint) { return address(this).balance; } // Set min house edge percent function setHouseEdgePercent(uint _houseEdgePercent) external onlyOwner { require ( _houseEdgePercent >= 1 && _houseEdgePercent <= 100, "houseEdgePercent must be a sane number"); houseEdgePercent = _houseEdgePercent; } // Set min bet amount. minBetAmount should be large enough such that its house edge fee can cover the Chainlink oracle fee. function setMinBetAmount(uint _minBetAmount) external onlyOwner { minBetAmount = _minBetAmount * 1 gwei; } // Set max bet amount. function setMaxBetAmount(uint _maxBetAmount) external onlyOwner { require (_maxBetAmount < 5000000 ether, "maxBetAmount must be a sane number"); maxBetAmount = _maxBetAmount; } // Set max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) external onlyOwner { require (_maxProfit < 50000000 ether, "maxProfit must be a sane number"); maxProfit = _maxProfit; } // Set wealth tax percentage to be added to house edge percent. Setting this to zero effectively disables wealth tax. function setWealthTaxIncrementPercent(uint _wealthTaxIncrementPercent) external onlyOwner { wealthTaxIncrementPercent = _wealthTaxIncrementPercent; } // Set threshold to trigger wealth tax. function setWealthTaxIncrementThreshold(uint _wealthTaxIncrementThreshold) external onlyOwner { wealthTaxIncrementThreshold = _wealthTaxIncrementThreshold; } // Owner can withdraw funds not exceeding balance minus potential win prizes by open bets function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Withdrawal amount larger than balance."); require (withdrawAmount <= address(this).balance - lockedInBets, "Withdrawal amount larger than balance minus lockedInBets"); beneficiary.transfer(withdrawAmount); cumulativeWithdrawal += withdrawAmount; } // Place bet function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable nonReentrant { Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); // Validate input data. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= minBetAmount && amount <= maxBetAmount, "Bet amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit)); address signer = ecrecover(signatureHash, 27, r, s); require (owner() == signer, "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games can specify exact bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos games specify the right edge of half-open interval of winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount. uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. Bet will not be placed if condition is not met. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Check whether contract has enough funds to accept this bet. require (lockedInBets + possibleWinAmount <= address(this).balance, "Unable to accept bet due to insufficient funds"); // Update lock funds. lockedInBets += possibleWinAmount; // Store bet bet.amount=amount; bet.modulo=uint8(modulo); bet.rollUnder=uint8(rollUnder); bet.mask=uint40(mask); bet.placeBlockNumber=block.number; bet.gambler=payable(msg.sender); bet.isSettled=false; bet.outcome=0; bet.winAmount=0; bet.randomNumber=0; bet.commit=commit; // Record bet in event logs emit BetPlaced(msg.sender, amount, uint8(modulo), uint8(rollUnder), uint40(mask), commit); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private view returns (uint winAmount) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); uint houseEdge = amount * (houseEdgePercent + getWealthTax(amount)) / 100; winAmount = (amount - houseEdge) * modulo / rollUnder; } // Get wealth tax function getWealthTax(uint amount) private view returns (uint wealthTax) { wealthTax = amount / wealthTaxIncrementThreshold * wealthTaxIncrementPercent; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyOwner { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number >= placeBlockNumber, "settleBet before placeBet"); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyOwner { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; // Validation check require (amount > 0, "Bet does not exist."); // Check that bet exists require(bet.isSettled == false, "Bet is settled already"); // Check that bet is not settled yet // Fetch bet parameters into local variables (to save gas). uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint outcome = uint(entropy) % modulo; // Win amount if gambler wins this bet uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder); // Actual win amount by gambler uint winAmount = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (outcome < rollUnder) { winAmount = possibleWinAmount; } } emitSettledEvent(bet, outcome, winAmount); // Unlock possibleWinAmount from lockedInBets, regardless of the outcome. lockedInBets -= possibleWinAmount; // Update bet records bet.isSettled = true; bet.winAmount = winAmount; bet.randomNumber = uint(entropy); bet.outcome = outcome; // Send win amount to gambler. if (winAmount > 0) { gambler.transfer(winAmount); } } function emitSettledEvent(Bet storage bet, uint outcome, uint winAmount) private { uint amount = bet.amount; // Fetch bet parameters into local variables (to save gas). uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; // Record bet settlement in event log. emit BetSettled(gambler, amount, uint8(modulo), uint8(rollUnder), bet.mask, outcome, winAmount); } // Return the bet in extremely unlikely scenario it was not settled by Chainlink VRF. // In case you ever find yourself in a situation like this, just contact Polyroll support. // However, nothing precludes you from calling this method yourself. function refundBet(uint commit) external nonReentrant payable { Bet storage bet = bets[commit]; uint amount = bet.amount; // Validation check require (amount > 0, "Bet does not exist."); // Check that bet exists require (bet.isSettled == false, "Bet is settled already."); // Check that bet is still open require (block.number > bet.placeBlockNumber + 43200, "Wait after placing bet before requesting refund."); uint possibleWinAmount = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); // Unlock possibleWinAmount from lockedInBets, regardless of the outcome. lockedInBets -= possibleWinAmount; // Update bet records bet.isSettled = true; bet.winAmount = amount; // Send the refund. bet.gambler.transfer(amount); // Record refund in event logs emit BetRefunded(bet.gambler, amount); } // This helpers are used to verify cryptographic proofs of placeBet inclusion into // uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without // compromising the security of the smart contract. Proof data is appended to the input data // in a simple prefix length format and does not adhere to the ABI. // Invariants checked: // - receipt trie entry contains a (1) successful transaction (2) directed at this smart // contract (3) containing commit as a payload. // - receipt trie entry is a part of a valid merkle proof of a block header // - the block header is a part of uncle list of some block on canonical chain // The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures. // Read the whitepaper for details. // Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof // beginning in the calldata. function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (;; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := keccak256(scratchBuf2, unclesLength) } offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) } } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(payable(owner())); } }
Place bet Validate input data. Check that commit is valid - it has not expired and its signature is valid. Small modulo games can specify exact bet outcomes via bit mask. rollUnder is a number of 1 bits in this mask (population count). This magic looking formula is an efficient way to compute population count on EVM for numbers below 240. Larger modulos games specify the right edge of half-open interval of winning bet outcomes.
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable nonReentrant { Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= minBetAmount && amount <= maxBetAmount, "Bet amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit)); address signer = ecrecover(signatureHash, 27, r, s); require (owner() == signer, "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } bet.modulo=uint8(modulo); bet.rollUnder=uint8(rollUnder); bet.mask=uint40(mask); bet.placeBlockNumber=block.number; bet.gambler=payable(msg.sender); bet.isSettled=false; bet.outcome=0; bet.winAmount=0; bet.randomNumber=0; bet.commit=commit; }
15,378,670
pragma solidity 0.5.12; library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(isContract(address(token)), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { require(initialOwner != address(0), "Ownable: initial owner is the zero address"); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_isOwner(msg.sender), "Ownable: caller is not the owner"); _; } function _isOwner(address account) internal view returns (bool) { return account == _owner; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title MinterRole */ contract MinterRole is Ownable { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; modifier onlyMinter() { require(isMinter(msg.sender), "Caller has no permission"); _; } function isMinter(address account) public view returns (bool) { return(_minters.has(account) || _isOwner(account)); } function addMinter(address account) public onlyOwner { _minters.add(account); emit MinterAdded(account); } function removeMinter(address account) public onlyOwner { _minters.remove(account); emit MinterRemoved(account); } } interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destroys `amount` tokens from msg.sender's balance. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. */ contract ERC20Mintable is ERC20Burnable, MinterRole { // if additional minting of tokens is impossible bool public mintingFinished; // prevent minting of tokens when it is finished. // prevent total supply to exceed the limit of emission. modifier canMint(uint256 amount) { require(amount > 0, "Minting zero amount"); require(!mintingFinished, "Minting is finished"); _; } /** * @dev Stop any additional minting of tokens forever. * Available only to the owner. */ function finishMinting() external onlyOwner { mintingFinished = true; } /** * @dev Minting of new tokens. * @param to The address to mint to. * @param value The amount to be minted. */ function mint(address to, uint256 value) public onlyMinter canMint(value) returns (bool) { _mint(to, value); return true; } } /** * @title ApproveAndCall Interface. * @dev ApproveAndCall system allows to communicate with smart-contracts. */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 amount, address token, bytes calldata extraData) external; } /** * @title The main project contract. */ contract MGTToken is ERC20Mintable, ERC20Detailed { using SafeERC20 for IERC20; using SafeMath for uint256; // registered contracts (to prevent loss of token via transfer function) mapping (address => bool) private _contracts; constructor(address initialOwner, address recipient) public ERC20Detailed("MeGold", "MGT", 4) Ownable(initialOwner) { // creating of inital supply uint256 INITIAL_SUPPLY = 5400000e4; _mint(recipient, INITIAL_SUPPLY); } /** * @dev modified transfer function that allows to safely send tokens to smart-contract. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { if (_contracts[to]) { approveAndCall(to, value, new bytes(0)); } else { super.transfer(to, value); } return true; } /** * @dev Allows to send tokens (via Approve and TransferFrom) to other smart-contract. * @param spender Address of smart contracts to work with. * @param amount Amount of tokens to send. * @param extraData Any extra data. */ function approveAndCall(address spender, uint256 amount, bytes memory extraData) public returns (bool) { require(approve(spender, amount)); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, amount, address(this), extraData); return true; } /** * @dev Allows to register other smart-contracts (to prevent loss of tokens via transfer function). * @param account Address of smart contracts to work with. */ function registerContract(address account) external onlyOwner { require(_isContract(account), "Token: account is not a smart contract"); _contracts[account] = true; } /** * @dev Allows to unregister registered smart-contracts. * @param account Address of smart contracts to work with. */ function unregisterContract(address account) external onlyOwner { require(isRegistered(account), "Token: account is not registered yet"); _contracts[account] = false; } /** * @dev Allows to any owner of the contract withdraw needed ERC20 token from this contract (for example promo or bounties). * @param ERC20Token Address of ERC20 token. * @param recipient Account to receive tokens. */ function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { uint256 amount = IERC20(ERC20Token).balanceOf(address(this)); IERC20(ERC20Token).safeTransfer(recipient, amount); } /** * @return true if the address is registered as contract * @param account Address to be checked. */ function isRegistered(address account) public view returns (bool) { return _contracts[account]; } /** * @return true if `account` is a contract. * @param account Address to be checked. */ function _isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } }
Minting of new tokens. to The address to mint to. value The amount to be minted./
function mint(address to, uint256 value) public onlyMinter canMint(value) returns (bool) { _mint(to, value); return true; }
507,206
pragma solidity 0.4.24; pragma experimental "v0.5.0"; interface RTCoinInterface { /** Functions - ERC20 */ function transfer(address _recipient, uint256 _amount) external returns (bool); function transferFrom(address _owner, address _recipient, uint256 _amount) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool approved); /** Getters - ERC20 */ function totalSupply() external view returns (uint256); function balanceOf(address _holder) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); /** Getters - Custom */ function mint(address _recipient, uint256 _amount) external returns (bool); function stakeContractAddress() external view returns (address); function mergedMinerValidatorAddress() external view returns (address); /** Functions - Custom */ function freezeTransfers() external returns (bool); function thawTransfers() external returns (bool); } library SafeMath { // We use `pure` bbecause it promises that the value for the function depends ONLY // on the function arguments function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /// @title TEMPORAL Payment Contract /// @author Postables, RTrade Technologies Ltd /// @dev We able V5 for safety features, see https://solidity.readthedocs.io/en/v0.4.24/security-considerations.html#take-warnings-seriously contract Payments { using SafeMath for uint256; // we mark as constant private to save gas bytes constant private PREFIX = "\x19Ethereum Signed Message:\n32"; // these addresses will need to be changed before deployment, and validated after deployment // we hardcode them for security reasons to avoid any possible risk of compromised accounts being able to change anything on this contract. // in the event that one of the addresses is compromised, the contract will be self destructed address constant private SIGNER = 0xa80cD01dD37c29116549AA879c44C824b703828A; address constant private TOKENADDRESS = 0xecc043b92834c1ebDE65F2181B59597a6588D616; address constant private HOTWALLET = 0x3eC6481365c2c2b37d7b939B5854BFB7e5e83C10; RTCoinInterface constant private RTI = RTCoinInterface(TOKENADDRESS); string constant public VERSION = "production"; address public admin; // PaymentState will keep track of the state of a payment, nil means we havent seen th payment before enum PaymentState{ nil, paid } // How payments can be made, RTC or eth enum PaymentMethod{ RTC, ETH } struct PaymentStruct { uint256 paymentNumber; uint256 chargeAmountInWei; PaymentMethod method; PaymentState state; } mapping (address => uint256) public numPayments; mapping (address => mapping(uint256 => PaymentStruct)) public payments; event PaymentMade(address _payer, uint256 _paymentNumber, uint8 _paymentMethod, uint256 _paymentAmount); modifier validPayment(uint256 _paymentNumber) { require(payments[msg.sender][_paymentNumber].state == PaymentState.nil, "payment already made"); _; } modifier onlyAdmin() { require(msg.sender == admin, "sender must be admin"); _; } constructor() public { admin = msg.sender; } /** @notice Used to submit a payment for TEMPORAL uploads * @dev Can use ERC191 or non ERC191 signed messages * @param _h This is the message hash that has been signed * @param _v This is pulled from the signature * @param _r This is pulled from the signature * @param _s This is pulled from the signature * @param _paymentNumber This is the current payments number (how many payments the user has submitted) * @param _paymentMethod This is the payment method (RTC, ETH) being used * @param _chargeAmountInWei This is how much the user is to be charged * @param _prefixed This indicates whether or not the signature was generated using ERC191 standards */ function makePayment( bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s, uint256 _paymentNumber, uint8 _paymentMethod, uint256 _chargeAmountInWei, bool _prefixed) // this allows us to sign messages on our own, without prefix https://github.com/ethereum/EIPs/issues/191 public payable validPayment(_paymentNumber) returns (bool) { require(_paymentMethod == 0 || _paymentMethod == 1, "invalid payment method"); bytes32 image; if (_prefixed) { bytes32 preimage = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); image = generatePrefixedPreimage(preimage); } else { image = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); } // ensure that the preimages construct properly require(image == _h, "reconstructed preimage does not match"); address signer = ecrecover(_h, _v, _r, _s); // ensure that we actually signed this message require(signer == SIGNER, "recovered signer does not match"); PaymentStruct memory ps = PaymentStruct({ paymentNumber: _paymentNumber, chargeAmountInWei: _chargeAmountInWei, method: PaymentMethod(_paymentMethod), state: PaymentState.paid }); payments[msg.sender][_paymentNumber] = ps; numPayments[msg.sender] = numPayments[msg.sender].add(1); // if they are opting to pay in eth run this block of code, otherwise make the payment in RTC if (PaymentMethod(_paymentMethod) == PaymentMethod.ETH) { require(msg.value == _chargeAmountInWei, "msg.value does not equal charge amount"); emit PaymentMade(msg.sender, _paymentNumber, _paymentMethod, _chargeAmountInWei); HOTWALLET.transfer(msg.value); return true; } emit PaymentMade(msg.sender, _paymentNumber, _paymentMethod, _chargeAmountInWei); require(RTI.transferFrom(msg.sender, HOTWALLET, _chargeAmountInWei), "trasferFrom failed, most likely needs approval"); return true; } /** @notice This is a helper function used to verify whether or not the provided arguments can reconstruct the message hash * @param _h This is the message hash which is signed, and will be reconstructed * @param _paymentNumber This is the number of payment * @param _paymentMethod This is the payment method (RTC, ETH) being used * @param _chargeAmountInWei This is the amount the user is to be charged * @param _prefixed This indicates whether the message was signed according to ERC191 */ function verifyImages( bytes32 _h, uint256 _paymentNumber, uint8 _paymentMethod, uint256 _chargeAmountInWei, bool _prefixed) public view returns (bool) { require(_paymentMethod == 0 || _paymentMethod == 1, "invalid payment method"); bytes32 image; if (_prefixed) { bytes32 preimage = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); image = generatePrefixedPreimage(preimage); } else { image = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); } return image == _h; } /** @notice This is a helper function which can be used to verify the signer of a message * @param _h This is the message hash that is signed * @param _v This is pulled from the signature * @param _r This is pulled from the signature * @param _s This is pulled from the signature * @param _paymentNumber This is the payment number of this particular payment * @param _paymentMethod This is the payment method (RTC, ETH) being used * @param _chargeAmountInWei This is the amount hte user is to be charged * @param _prefixed This indicates whether or not the message was signed using ERC191 */ function verifySigner( bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s, uint256 _paymentNumber, uint8 _paymentMethod, uint256 _chargeAmountInWei, bool _prefixed) public view returns (bool) { require(_paymentMethod == 0 || _paymentMethod == 1, "invalid payment method"); bytes32 image; if (_prefixed) { bytes32 preimage = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); image = generatePrefixedPreimage(preimage); } else { image = generatePreimage(_paymentNumber, _chargeAmountInWei, _paymentMethod); } require(image == _h, "failed to reconstruct preimages"); return ecrecover(_h, _v, _r, _s) == SIGNER; } /** @notice This is a helper function used to generate a non ERC191 signed message hash * @param _paymentNumber This is the payment number of this payment * @param _chargeAmountInWei This is the amount the user is to be charged * @param _paymentMethod This is the payment method (RTC, ETH) being used */ function generatePreimage( uint256 _paymentNumber, uint256 _chargeAmountInWei, uint8 _paymentMethod) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, _paymentNumber, _paymentMethod, _chargeAmountInWei)); } /** @notice This is a helper function that prepends the ERC191 signed message prefix * @param _preimage This is the reconstructed message hash before being prepened with the ERC191 prefix */ function generatePrefixedPreimage(bytes32 _preimage) internal pure returns (bytes32) { return keccak256(abi.encodePacked(PREFIX, _preimage)); } /** @notice Used to destroy the contract */ function goodNightSweetPrince() public onlyAdmin returns (bool) { selfdestruct(msg.sender); return true; } }
This is a helper function that prepends the ERC191 signed message prefix _preimage This is the reconstructed message hash before being prepened with the ERC191 prefix/
function generatePrefixedPreimage(bytes32 _preimage) internal pure returns (bytes32) { return keccak256(abi.encodePacked(PREFIX, _preimage)); }
7,626,642
./full_match/1/0xCfE7a48f89C24c9ACEA8B9735A1415C71b30E4BD/sources/src/EnhancedVestingWalletFactory.sol
Returns `true` if given `wallet` was created by this factory./
function isWalletFromFactory(address wallet) external view returns (bool) { return _isFromFactory[wallet]; }
3,178,495
pragma solidity ^0.5.16; import "./CToken.sol"; import "./ERC3156FlashLenderInterface.sol"; import "./ERC3156FlashBorrowerInterface.sol"; /** * @title Cream's CCollateralCapErc20 Contract * @notice CTokens which wrap an EIP-20 underlying with collateral cap * @author Cream */ contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external returns (uint256) { (uint256 err, ) = mintInternal(mintAmount, false); require(err == 0, "mint failed"); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { require(redeemInternal(redeemTokens, false) == 0, "redeem failed"); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256) { require(redeemUnderlyingInternal(redeemAmount, false) == 0, "redeem underlying failed"); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256) { require(borrowInternal(borrowAmount, false) == 0, "borrow failed"); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount, false); require(err == 0, "repay failed"); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false); require(err == 0, "repay behalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral, false); require(err == 0, "liquidate borrow failed"); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint256 addAmount) external returns (uint256) { require(_addReservesInternal(addAmount, false) == 0, "add reserves failed"); } /** * @notice Set the given collateral cap for the market. * @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap. */ function _setCollateralCap(uint256 newCollateralCap) external { require(msg.sender == admin, "admin only"); collateralCap = newCollateralCap; emit NewCollateralCap(address(this), newCollateralCap); } /** * @notice Absorb excess cash into reserves. */ function gulp() external nonReentrant { uint256 cashOnChain = getCashOnChain(); uint256 cashPrior = getCashPrior(); uint256 excessCash = sub_(cashOnChain, cashPrior); totalReserves = add_(totalReserves, excessCash); internalCash = cashOnChain; } /** * @notice Get the max flash loan amount */ function maxFlashLoan() external view returns (uint256) { uint256 amount = 0; if ( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, "") ) { amount = getCashPrior(); } return amount; } /** * @notice Get the flash loan fees * @param amount amount of token to borrow */ function flashFee(uint256 amount) external view returns (uint256) { require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, ""), "flashloan is paused" ); return div_(mul_(amount, flashFeeBips), 10000); } /** * @notice Flash loan funds to a given account. * @param receiver The receiver address for the funds * @param initiator flash loan initiator * @param amount The amount of the funds to be loaned * @param data The other data * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external nonReentrant returns (bool) { require(amount > 0, "invalid flashloan amount"); accrueInterest(); require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed( address(this), address(receiver), amount, data ), "flashloan is paused" ); uint256 cashOnChainBefore = getCashOnChain(); uint256 cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint256 totalFee = this.flashFee(amount); // 2. transfer fund to receiver doTransferOut(address(uint160(address(receiver))), amount, false); // 3. update totalBorrows totalBorrows = add_(totalBorrows, amount); // 4. execute receiver's callback function require( receiver.onFlashLoan(initiator, underlying, amount, totalFee, data) == keccak256("ERC3156FlashBorrowerInterface.onFlashLoan"), "IERC3156: Callback failed" ); // 5. take amount + fee from receiver, then check balance uint256 repaymentAmount = add_(amount, totalFee); doTransferIn(address(receiver), repaymentAmount, false); uint256 cashOnChainAfter = getCashOnChain(); require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT"); // 6. update reserves and internal cash and totalBorrows uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); internalCash = add_(cashBefore, totalFee); totalBorrows = sub_(totalBorrows, amount); emit Flashloan(address(receiver), amount, totalFee, reservesFee); return true; } /** * @notice Register account collateral tokens if there is space. * @param account The account to register * @dev This function could only be called by comptroller. * @return The actual registered amount of collateral */ function registerCollateral(address account) external returns (uint256) { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "comptroller only"); uint256 amount = sub_(accountTokens[account], accountCollateralTokens[account]); return increaseUserCollateralInternal(account, amount); } /** * @notice Unregister account collateral tokens if the account still has enough collateral. * @dev This function could only be called by comptroller. * @param account The account to unregister */ function unregisterCollateral(address account) external { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "comptroller only"); require(comptroller.redeemAllowed(address(this), account, accountCollateralTokens[account]) == 0, "rejected"); decreaseUserCollateralInternal(account, accountCollateralTokens[account]); } /*** Safe Token ***/ /** * @notice Gets internal balance of this contract in terms of the underlying. * It excludes balance from direct transfer. * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { return internalCash; } /** * @notice Gets total balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashOnChain() internal view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function * that accesses accountCollateralTokens or accountTokens. * @param account The account of accountCollateralTokens that needs to be updated */ function initializeAccountCollateralTokens(address account) internal { /** * If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet. * This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its * initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to * check every user's value when the implementation becomes active. Therefore, it must rely on every action which will * access accountTokens to call this function to check if accountCollateralTokens needed to be initialized. */ if (!isCollateralTokenInit[account]) { if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(account, CToken(this))) { accountCollateralTokens[account] = accountTokens[account]; totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]); emit UserCollateralChanged(account, accountCollateralTokens[account]); } isCollateralTokenInit[account] = true; } } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "transfer failed"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); uint256 transferredIn = sub_(balanceAfter, balanceBefore); internalCash = add_(internalCash, transferredIn); return transferredIn; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "transfer failed"); internalCash = sub_(internalCash, amount); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { // Make sure accountCollateralTokens of `src` and `dst` are initialized. initializeAccountCollateralTokens(src); initializeAccountCollateralTokens(dst); /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be transferred first. * bufferTokens = accountTokens[src] - accountCollateralTokens[src] * collateralTokens = tokens - bufferTokens */ uint256 bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]); uint256 collateralTokens = 0; if (tokens > bufferTokens) { collateralTokens = tokens - bufferTokens; } /** * Since bufferTokens are not collateralized and can be transferred freely, we only check with comptroller * whether collateralized tokens can be transferred. */ require(comptroller.transferAllowed(address(this), src, dst, collateralTokens) == 0, "rejected"); /* Do not allow self-transfers */ require(src != dst, "bad input"); /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ accountTokens[src] = sub_(accountTokens[src], tokens); accountTokens[dst] = add_(accountTokens[dst], tokens); if (collateralTokens > 0) { accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens); accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens); emit UserCollateralChanged(src, accountCollateralTokens[src]); emit UserCollateralChanged(dst, accountCollateralTokens[dst]); } /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = sub_(startingAllowance, tokens); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @notice Get the account's cToken balances * @param account The address of the account */ function getCTokenBalanceInternal(address account) internal view returns (uint256) { if (isCollateralTokenInit[account]) { return accountCollateralTokens[account]; } else { /** * If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens. */ return accountTokens[account]; } } /** * @notice Increase user's collateral. Increase as much as we can. * @param account The address of the account * @param amount The amount of collateral user wants to increase * @return The actual increased amount of collateral */ function increaseUserCollateralInternal(address account, uint256 amount) internal returns (uint256) { uint256 totalCollateralTokensNew = add_(totalCollateralTokens, amount); if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) { // 1. If collateral cap is not set, // 2. If collateral cap is set but has enough space for this user, // give all the user needs. totalCollateralTokens = totalCollateralTokensNew; accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); return amount; } else if (collateralCap > totalCollateralTokens) { // If the collateral cap is set but the remaining cap is not enough for this user, // give the remaining parts to the user. uint256 gap = sub_(collateralCap, totalCollateralTokens); totalCollateralTokens = add_(totalCollateralTokens, gap); accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap); emit UserCollateralChanged(account, accountCollateralTokens[account]); return gap; } return 0; } /** * @notice Decrease user's collateral. Reject if the amount can't be fully decrease. * @param account The address of the account * @param amount The amount of collateral user wants to decrease */ function decreaseUserCollateralInternal(address account, uint256 amount) internal { /* * Return if amount is zero. * Put behind `redeemAllowed` for accuring potential COMP rewards. */ if (amount == 0) { return; } totalCollateralTokens = sub_(totalCollateralTokens, amount); accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); } struct MintLocalVars { uint256 exchangeRateMantissa; uint256 mintTokens; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256) { // Make sure accountCollateralTokens of `minter` is initialized. initializeAccountCollateralTokens(minter); /* Fail if mint not allowed */ require(comptroller.mintAllowed(address(this), minter, mintAmount) == 0, "rejected"); /* * Return if mintAmount is zero. * Put behind `mintAllowed` for accuring potential COMP rewards. */ if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupply = totalSupply + mintTokens * accountTokens[minter] = accountTokens[minter] + mintTokens */ totalSupply = add_(totalSupply, vars.mintTokens); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); /* * We only allocate collateral tokens if the minter has entered the market. */ if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(this))) { increaseUserCollateralInternal(minter, vars.mintTokens); } /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } struct RedeemLocalVars { uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero. * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256) { // Make sure accountCollateralTokens of `redeemer` is initialized. initializeAccountCollateralTokens(redeemer); require(redeemTokensIn == 0 || redeemAmountIn == 0, "bad input"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be redeemed first. * bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer] * collateralTokens = redeemTokens - bufferTokens */ uint256 bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]); uint256 collateralTokens = 0; if (vars.redeemTokens > bufferTokens) { collateralTokens = vars.redeemTokens - bufferTokens; } /* redeemAllowed might check more than user's liquidity. */ require(comptroller.redeemAllowed(address(this), redeemer, collateralTokens) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= vars.redeemAmount, "insufficient cash"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ totalSupply = sub_(totalSupply, vars.redeemTokens); accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens); /* * We only deallocate collateral tokens if the redeemer needs to redeem them. */ decreaseUserCollateralInternal(redeemer, collateralTokens); /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount, isNative); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint256(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { // Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized. initializeAccountCollateralTokens(liquidator); initializeAccountCollateralTokens(borrower); /* Fail if seize not allowed */ require( comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens) == 0, "rejected" ); /* * Return if seizeTokens is zero. * Put behind `seizeAllowed` for accuring potential COMP rewards. */ if (seizeTokens == 0) { return uint256(Error.NO_ERROR); } /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* * We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow: * accountTokens[borrower] = accountTokens[borrower] - seizeTokens * accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens * accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens * accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens */ accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens); accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens); accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens); accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], seizeTokens); /* Emit a Transfer, UserCollateralChanged events */ emit Transfer(borrower, liquidator, seizeTokens); emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]); emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint256(Error.NO_ERROR); } } pragma solidity ^0.5.16; import "./CCollateralCapErc20.sol"; /** * @title Cream's CCollateralCapErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Cream */ contract CCollateralCapErc20Delegate is CCollateralCapErc20 { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "admin only"); // Set internal cash when becoming implementation internalCash = getCashOnChain(); // Set CToken version in comptroller ComptrollerInterfaceExtension(address(comptroller)).updateCTokenVersion( address(this), ComptrollerV1Storage.Version.COLLATERALCAP ); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "admin only"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "admin only"); require(accrualBlockNumber == 0 && borrowIndex == 0, "initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "invalid exchange rate"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "failed to set comptroller"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "failed to set IRM"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ require(comptroller.borrowAllowed(address(this), borrower, borrowAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= borrowAmount, "insufficient cash"); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ require(comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); require(cTokenCollateral.accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ require( comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ) == 0, "rejected" ); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Verify cTokenCollateral market's block number equals current block number */ require(cTokenCollateral.accrualBlockNumber() == getBlockNumber(), "market is stale"); /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* Fail if repayAmount = 0 or repayAmount = -1 */ require(repayAmount > 0 && repayAmount != uint256(-1), "invalid close amount requested"); LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); require(vars.repayBorrowError == uint256(Error.NO_ERROR), "repay borrow failed"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require(vars.amountSeizeError == uint256(Error.NO_ERROR), "failed to calculate seize amount"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "not comptroller"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in wrapped token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, false); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "invalid IRM"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives /// @dev This storage is depreacted. mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user /// @dev This storage is depreacted. mapping(address => uint256) public compAccrued; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice creditLimits allowed specific protocols to borrow and repay without collateral. /// @dev This storage is depreacted. mapping(address => uint256) public _creditLimits; /// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; /// @notice creditLimits allowed specific protocols to borrow and repay specific markets without collateral. mapping(address => mapping(address => uint256)) public creditLimits; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; import "./ERC3156FlashBorrowerInterface.sol"; interface ERC3156FlashLenderInterface { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( ERC3156FlashBorrowerInterface receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); }
Gets internal balance of this contract in terms of the underlying. It excludes balance from direct transfer. This excludes the value of the current message, if any return The quantity of underlying tokens owned by this contract/
function getCashPrior() internal view returns (uint256) { return internalCash; }
1,445,610
./partial_match/8453/0x233dc79F924c35AcB4524BaC4A883c8CE11A75B2/sources/src/Bridge.sol
Overiding the _nonblockingLzReceive function to handle minting of the token. _payload The payload received
function _nonblockingLzReceive(uint16, bytes memory, uint64, bytes memory _payload) internal override { uint8 packetType = _payload.toUint8(0); if (packetType == PT_SEND) { (address _to, uint256 _amount) = _decodeSendPayload(_payload); _mint(_to, uint256(_amount)); (, address _to, uint64 _amount,,) = _decodeSendAndCallPayload(_payload); _mint(_to, uint256(_amount)); revert("OFTCore: unknown packet type"); } }
16,694,688
./partial_match/1/0x242d6E16653b30c830C1918b5Cc23d27253B2d26/sources/ProxyERC20.sol
Returns true if `account` is a contract. [IMPORTANT] ==== It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the following types of addresses: - an externally-owned account - a contract in construction - an address where a contract will be created - an address where a contract lived, but was destroyed ==== [IMPORTANT] ==== You shouldn't rely on `isContract` to protect against flash loan attacks! Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract constructor. ====/ This method relies on extcodesize/address.code.length, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.
function _debitFrom(address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount) internal virtual; function _creditTo(uint16 _srcChainId, address _toAddress, uint _amount) internal virtual; } pragma solidity ^0.8.0; } pragma solidity ^0.8.1; function isContract(address account) internal view returns (bool) { return account.code.length > 0; }
15,547,715
./full_match/4/0x985eC2799A6cbD9E07c6324A6cA4D5612a93852D/sources/tenderly/project/contracts/dex-v2/pool/VaderPoolV2.sol
Sets the supported state of the token represented by param {foreignAsset}. Requirements: - The param {foreignAsset} is not already a supported token./
function setTokenSupport(IERC20 foreignAsset, bool support) external override onlyOwner { require( supported[foreignAsset] != support, "VaderPoolV2::supportToken: Already At Desired State" ); supported[foreignAsset] = support; }
12,372,428
pragma solidity 0.5.15; import 'ROOT/gsn/v1/RLPReader.sol'; import 'ROOT/gsn/v1/GSNRecipient.sol'; import 'ROOT/gsn/v1/IRelayHub.sol'; import 'ROOT/IAugur.sol'; import 'ROOT/IAugurWallet.sol'; import 'ROOT/AugurWallet.sol'; import 'ROOT/trading/IAugurTrading.sol'; import 'ROOT/libraries/Initializable.sol'; import 'ROOT/libraries/token/IERC1155.sol'; import 'ROOT/libraries/math/SafeMathUint256.sol'; import 'ROOT/libraries/LibBytes.sol'; import 'ROOT/libraries/ContractExists.sol'; import 'ROOT/uniswap/interfaces/IUniswapV2Factory.sol'; import 'ROOT/uniswap/interfaces/IUniswapV2Pair.sol'; import 'ROOT/uniswap/interfaces/IWETH.sol'; import 'ROOT/factories/IAugurWalletFactory.sol'; contract AugurWalletRegistry is Initializable, GSNRecipient { using LibBytes for bytes; using ContractExists for address; using SafeMathUint256 for uint256; enum GSNRecipientERC20FeeErrorCodes { OK, TX_COST_TOO_HIGH, INSUFFICIENT_BALANCE } event ExecuteTransactionStatus(bool success, bool fundingSuccess); IAugur public augur; IAugurTrading public augurTrading; IERC20 public cash; IUniswapV2Pair public ethExchange; IWETH public WETH; bool public token0IsCash; IAugurWalletFactory public augurWalletFactory; uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1; uint256 private constant MAX_TX_FEE_IN_ETH = 10**17; function initialize(IAugur _augur, IAugurTrading _augurTrading) public payable beforeInitialized returns (bool) { require(msg.value >= MAX_TX_FEE_IN_ETH, "Must provide initial Max TX Fee Deposit"); endInitialization(); augur = _augur; cash = IERC20(_augur.lookup("Cash")); augurTrading = _augurTrading; WETH = IWETH(_augurTrading.lookup("WETH9")); augurWalletFactory = IAugurWalletFactory(_augurTrading.lookup("AugurWalletFactory")); IUniswapV2Factory _uniswapFactory = IUniswapV2Factory(_augur.lookup("UniswapV2Factory")); address _ethExchangeAddress = _uniswapFactory.getPair(address(WETH), address(cash)); if (_ethExchangeAddress == address(0)) { _ethExchangeAddress = _uniswapFactory.createPair(address(WETH), address(cash)); } ethExchange = IUniswapV2Pair(_ethExchangeAddress); token0IsCash = ethExchange.token0() == address(cash); IRelayHub(getHubAddr()).depositFor.value(address(this).balance)(address(this)); return true; } function acceptRelayedCall( address, address _from, bytes calldata _encodedFunction, uint256, uint256, uint256, uint256, bytes calldata, uint256 _maxPossibleCharge ) external view returns (uint256 _reason, bytes memory _context) { // executeWalletTransaction is the only encodedFunction that can succesfully be called through the relayHub uint256 _payment = getPaymentFromEncodedFunction(_encodedFunction); GSNRecipientERC20FeeErrorCodes _code = getAcceptRelayCallStatus(_from, _payment, _maxPossibleCharge); if (_code != GSNRecipientERC20FeeErrorCodes.OK) { return _rejectRelayedCall(uint256(_code)); } uint256 _initialEth = address(this).balance; return _approveRelayedCall(abi.encode(_from, _initialEth)); } function getPaymentFromEncodedFunction(bytes memory _encodedFunction) private pure returns (uint256) { bytes memory _encodedFunctionParams = _encodedFunction.sliceDestructive(4, _encodedFunction.length); (address _to, bytes memory _data, uint256 _value, uint256 _payment, address _affilate, bytes32 _fingerprint) = abi.decode(_encodedFunctionParams, (address, bytes, uint256, uint256, address, bytes32)); return _payment; } function getAcceptRelayCallStatus(address _from, uint256 _payment, uint256 _maxPossibleCharge) private view returns (GSNRecipientERC20FeeErrorCodes _code) { (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _maxDaiNeeded = getAmountIn(_maxPossibleCharge, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); if (_maxDaiNeeded > _payment) { return GSNRecipientERC20FeeErrorCodes.TX_COST_TOO_HIGH; } if (cash.balanceOf(getCreate2WalletAddress(_from)) < _payment) { return GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE; } return GSNRecipientERC20FeeErrorCodes.OK; } function _preRelayedCall(bytes memory _context) internal returns (bytes32) { } function _postRelayedCall(bytes memory _context, bool, uint256 _actualCharge, bytes32) internal { (address _from, uint256 _initialEth) = abi.decode(_context, (address, uint256)); // Refund any excess ETH paid back to the wallet uint256 _ethPaid = address(this).balance.sub(_initialEth); uint256 _ethRefund = _ethPaid.sub(_actualCharge); (bool _success,) = address(_from).call.value(_ethRefund)(""); require(_success); // Top off Relay Hub balance with whatever ETH we have uint256 _depositAmount = address(this).balance; _depositAmount = _depositAmount.min(2 ether); // This is the maximum single RelayHub deposit IRelayHub(getHubAddr()).depositFor.value(_depositAmount)(address(this)); } function getEthFromWallet(IAugurWallet _wallet, uint256 _cashAmount) private { (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _ethAmount = getAmountOut(_cashAmount, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); _wallet.transferCash(address(ethExchange), _cashAmount); ethExchange.swap(token0IsCash ? 0 : _ethAmount, token0IsCash ? _ethAmount : 0, address(this), ""); WETH.withdraw(_ethAmount); } // Returns whether the signer eth balance was funded as desired function fundMsgSender(uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai) private returns (bool) { address _msgSender = address(_msgSender()); IAugurWallet _wallet = getWallet(_msgSender); uint256 _msgSenderBalance = _msgSender.balance; if (_msgSenderBalance >= _desiredSignerBalance) { return true; } uint256 _ethDelta = _desiredSignerBalance - _msgSenderBalance; (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _cashAmount = getAmountIn(_ethDelta, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethDelta); if (_maxExchangeRateInDai < _exchangeRate) { return false; } _wallet.transferCash(address(ethExchange), _cashAmount); ethExchange.swap(token0IsCash ? 0 : _ethDelta, token0IsCash ? _ethDelta : 0, address(this), ""); WETH.withdraw(_ethDelta); (bool _success,) = _msgSender.call.value(_ethDelta)(""); return _success; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) { require(amountIn > 0); require(reserveIn > 0 && reserveOut > 0); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure returns (uint amountIn) { require(amountOut > 0); require(reserveIn > 0 && reserveOut > 0); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function createAugurWallet(address _referralAddress, bytes32 _fingerprint) private returns (IAugurWallet) { return augurWalletFactory.createAugurWallet(_msgSender(), _referralAddress, _fingerprint); } function getCreate2WalletAddress(address _owner) public view returns (address) { return augurWalletFactory.getCreate2WalletAddress(_owner); } /** * @notice Get the Wallet for the given account * @param _account The account to look up * @return IAugurWallet for the account or 0x if none exists */ function getWallet(address _account) public view returns (IAugurWallet) { address _walletAddress = getCreate2WalletAddress(_account); if (!_walletAddress.exists()) { return IAugurWallet(0); } return IAugurWallet(_walletAddress); } // 1. Create a user's wallet if it does not exist // 2. Get funds from the wallet to compensate this contract for paying the relayer // 3. Execute the transaction and return success status, or revert if appropriate // 4. Fund the signer with ETH as specified function executeWalletTransaction(address _to, bytes calldata _data, uint256 _value, uint256 _payment, address _referralAddress, bytes32 _fingerprint, uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai, bool _revertOnFailure) external { address _user = _msgSender(); IAugurWallet _wallet = getWallet(_user); if (_wallet == IAugurWallet(0)) { _wallet = createAugurWallet(_referralAddress, _fingerprint); } // If the user is having this sent via relay we need to reimburse this contract for paying the relayer. We do the payment here to avoid hard coded gas stipend problems in GSN V1 if (_user != msg.sender) { getEthFromWallet(_wallet, _payment); } bool _success = _wallet.executeTransaction(_to, _data, _value); // We need to be able to fail in order to get accurate gas estimates. We only allow this however when not using the relayhub since otherwise funds could be drained this way if (_user == msg.sender && _revertOnFailure) { require(_success, "Transaction Execution Failed"); } // We keep the signing account's ETH balance funded up to an offchain provided value so it can send txs itself without the use of a relay bool _fundingSuccess = fundMsgSender(_desiredSignerBalance, _maxExchangeRateInDai); emit ExecuteTransactionStatus(_success, _fundingSuccess); } function getRelayMessageHash( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce) public view returns (bytes32) { bytes memory packed = abi.encodePacked("rlx:", from, to, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, getHubAddr()); return keccak256(abi.encodePacked(packed, relay)); } function () external payable {} }
Get the Wallet for the given account _account The account to look up return IAugurWallet for the account or 0x if none exists/
function getWallet(address _account) public view returns (IAugurWallet) { address _walletAddress = getCreate2WalletAddress(_account); if (!_walletAddress.exists()) { return IAugurWallet(0); } return IAugurWallet(_walletAddress); }
1,041,554
// ---------------------------------------------------------------------------------------------- // Developer Nechesov Andrey & ObjectMicro, Inc // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Bqt_Token is ERC20Interface { string public constant symbol = "BQT"; string public constant name = "BQT token"; uint8 public constant decimals = 18; uint256 public constant maxTokens = 800*10**6*10**18; uint256 public constant ownerSupply = maxTokens*51/100; uint256 _totalSupply = ownerSupply; uint256 public constant token_price = 10**18*1/800; uint256 public pre_ico_start = 1528416000; // Jun 8, 2018 utc uint256 public ico_start = 1531008000; // Jul 8, 2018 utc uint256 public ico_finish = 1541635200; // Nov 8, 2018 utc uint public constant minValuePre = 10**18*1/1000000; uint public constant minValue = 10**18*1/1000000; uint public constant maxValue = 3000*10**18; uint8 public constant exchange_coefficient = 102; using SafeMath for uint; // Owner of this contract address public owner; address public moderator; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Orders holders who wish sell tokens, save amount mapping(address => uint256) public orders_sell_amount; // Orders holders who wish sell tokens, save price mapping(address => uint256) public orders_sell_price; //orders list address[] public orders_sell_list; // Triggered on set SELL order event Order_sell(address indexed _owner, uint256 _max_amount, uint256 _price); // Triggered on execute SELL order event Order_execute(address indexed _from, address indexed _to, uint256 _amount, uint256 _price); // Functions with this modifier can only be executed by the owner modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } // Functions with this modifier can only be executed by the moderator modifier onlyModerator() { if (msg.sender != moderator) { throw; } _; } // Functions change owner function changeOwner(address _owner) onlyOwner returns (bool result) { owner = _owner; return true; } // Functions change moderator function changeModerator(address _moderator) onlyOwner returns (bool result) { moderator = _moderator; return true; } // Constructor function Bqt_Token() { //owner = msg.sender; owner = 0x3d143e5f256a4fbc16ef23b29aadc0db67bf0ec2; moderator = 0x788C45Dd60aE4dBE5055b5Ac02384D5dc84677b0; balances[owner] = ownerSupply; } //default function function() payable { tokens_buy(); } function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } //Withdraw money from contract balance to owner function withdraw(uint256 _amount) onlyOwner returns (bool result) { uint256 balance; balance = this.balance; if(_amount > 0) balance = _amount; owner.send(balance); return true; } //Change pre_ico_start date function change_pre_ico_start(uint256 _pre_ico_start) onlyModerator returns (bool result) { pre_ico_start = _pre_ico_start; return true; } //Change ico_start date function change_ico_start(uint256 _ico_start) onlyModerator returns (bool result) { ico_start = _ico_start; return true; } //Change ico_finish date function change_ico_finish(uint256 _ico_finish) onlyModerator returns (bool result) { ico_finish = _ico_finish; return true; } // Total tokens on user address function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } //Return param, how many tokens can send _spender from _owner account function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Buy tokens on pre-ico and ico with bonuses on time boundaries */ function tokens_buy() payable returns (bool) { uint256 tnow = now; //if(tnow < pre_ico_start) throw; if(tnow > ico_finish) throw; if(_totalSupply >= maxTokens) throw; if(!(msg.value >= token_price)) throw; if(!(msg.value >= minValue)) throw; if(msg.value > maxValue) throw; uint tokens_buy = (msg.value*10**18).div(token_price); uint tokens_buy_total; if(!(tokens_buy > 0)) throw; //Bonus for total tokens amount for all contract uint b1 = 0; //Time bonus on Pre-ICO && ICO uint b2 = 0; //Individual bonus for tokens amount uint b3 = 0; if(_totalSupply <= 5*10**6*10**18) { b1 = tokens_buy*30/100; } if((5*10**6*10**18 < _totalSupply)&&(_totalSupply <= 10*10**6*10**18)) { b1 = tokens_buy*25/100; } if((10*10**6*10**18 < _totalSupply)&&(_totalSupply <= 15*10**6*10**18)) { b1 = tokens_buy*20/100; } if((15*10**6*10**18 < _totalSupply)&&(_totalSupply <= 20*10**6*10**18)) { b1 = tokens_buy*15/100; } if((20*10**6*10**18 < _totalSupply)&&(_totalSupply <= 25*10**6*10**18)) { b1 = tokens_buy*10/100; } if(25*10**6*10**18 <= _totalSupply) { b1 = tokens_buy*5/100; } if(tnow < ico_start) { b2 = tokens_buy*50/100; } if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*5)){ b2 = tokens_buy*10/100; } if((ico_start + 86400*5 <= tnow)&&(tnow < ico_start + 86400*10)){ b2 = tokens_buy*8/100; } if((ico_start + 86400*10 <= tnow)&&(tnow < ico_start + 86400*20)){ b2 = tokens_buy*6/100; } if((ico_start + 86400*20 <= tnow)&&(tnow < ico_start + 86400*30)){ b2 = tokens_buy*4/100; } if(ico_start + 86400*30 <= tnow){ b2 = tokens_buy*2/100; } if((1000*10**18 <= tokens_buy)&&(5000*10**18 <= tokens_buy)) { b3 = tokens_buy*5/100; } if((5001*10**18 <= tokens_buy)&&(10000*10**18 < tokens_buy)) { b3 = tokens_buy*10/100; } if((10001*10**18 <= tokens_buy)&&(15000*10**18 < tokens_buy)) { b3 = tokens_buy*15/100; } if((15001*10**18 <= tokens_buy)&&(20000*10**18 < tokens_buy)) { b3 = tokens_buy*20/100; } if(20001*10**18 <= tokens_buy) { b3 = tokens_buy*25/100; } tokens_buy_total = tokens_buy.add(b1); tokens_buy_total = tokens_buy_total.add(b2); tokens_buy_total = tokens_buy_total.add(b3); if(_totalSupply.add(tokens_buy_total) > maxTokens) throw; _totalSupply = _totalSupply.add(tokens_buy_total); balances[msg.sender] = balances[msg.sender].add(tokens_buy_total); return true; } /** * Get total SELL orders */ function orders_sell_total () constant returns (uint256) { return orders_sell_list.length; } /** * Get how many tokens can buy from this SELL order */ function get_orders_sell_amount(address _from) constant returns(uint) { uint _amount_max = 0; if(!(orders_sell_amount[_from] > 0)) return _amount_max; if(balanceOf(_from) > 0) _amount_max = balanceOf(_from); if(orders_sell_amount[_from] < _amount_max) _amount_max = orders_sell_amount[_from]; return _amount_max; } /** * User create SELL order. */ function order_sell(uint256 _max_amount, uint256 _price) returns (bool) { if(!(_max_amount > 0)) throw; if(!(_price > 0)) throw; orders_sell_amount[msg.sender] = _max_amount; orders_sell_price[msg.sender] = (_price*exchange_coefficient).div(100); orders_sell_list.push(msg.sender); Order_sell(msg.sender, _max_amount, orders_sell_price[msg.sender]); return true; } /** * Order Buy tokens - it's order search sell order from user _from and if all ok, send token and money */ function order_buy(address _from, uint256 _max_price) payable returns (bool) { if(!(msg.value > 0)) throw; if(!(_max_price > 0)) throw; if(!(orders_sell_amount[_from] > 0)) throw; if(!(orders_sell_price[_from] > 0)) throw; if(orders_sell_price[_from] > _max_price) throw; uint _amount = (msg.value*10**18).div(orders_sell_price[_from]); uint _amount_from = get_orders_sell_amount(_from); if(_amount > _amount_from) _amount = _amount_from; if(!(_amount > 0)) throw; uint _total_money = (orders_sell_price[_from]*_amount).div(10**18); if(_total_money > msg.value) throw; uint _seller_money = (_total_money*100).div(exchange_coefficient); uint _buyer_money = msg.value - _total_money; if(_seller_money > msg.value) throw; if(_seller_money + _buyer_money > msg.value) throw; if(_seller_money > 0) _from.send(_seller_money); if(_buyer_money > 0) msg.sender.send(_buyer_money); orders_sell_amount[_from] -= _amount; balances[_from] -= _amount; balances[msg.sender] += _amount; Order_execute(_from, msg.sender, _amount, orders_sell_price[_from]); } }
Change pre_ico_start date
function change_pre_ico_start(uint256 _pre_ico_start) onlyModerator returns (bool result) { pre_ico_start = _pre_ico_start; return true; }
1,480,064
pragma solidity 0.5.8; /// @notice https://eips.ethereum.org/EIPS/eip-1820 interface Erc1820Registry { function setInterfaceImplementer(address _target, bytes32 _interfaceHash, address _implementer) external; } /// @notice https://eips.ethereum.org/EIPS/eip-777 contract Erc777TokensRecipient { constructor() public { // keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b Erc1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24).setInterfaceImplementer(address(this), 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b, address(this)); } /// @notice called when someone attempts to transfer ERC-777 tokens to this address. If this function were to throw or doesn't exist, then the token transfer would fail. function tokensReceived(address, address, address, uint256, bytes calldata, bytes calldata) external { } /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `_implementer` or not. /// @param _interfaceHash keccak256 hash of the name of the interface /// @param _implementer Address for which the contract will implement the interface /// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `_implementer`. function canImplementInterfaceForAddress(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) { // keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b if (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b) { // keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")) == 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4 return 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; } else { return bytes32(0); } } } /// @notice An Ownable contract is one that has a single address that has elevated control over the contract's operations. Ownership can be transferred between users as a two-step process, one to initiate the transfer and two to receive the transfer. This two-step process ensures that ownership cannot accidentally be given to an address that cannot operate the contract. contract Ownable { event OwnershipTransferStarted(address indexed owner, address indexed pendingOwner); event OwnershipTransferCancelled(address indexed owner, address indexed pendingOwner); event OwnershipTransferFinished(address indexed oldOwner, address indexed newOwner); address public owner; address public pendingOwner; constructor(address _owner) public { require(_owner != address(0), "Contract must have an owner."); owner = _owner; } /// @notice a function modifier that ensures the modified function can only be called by the owner of the contract. modifier onlyOwner() { require(msg.sender == owner, "Only the owner may call this method."); _; } /// @notice starts the transfer of ownership to a new owner. /// @param _pendingOwner the address to which ownership should be transferred. function startOwnershipTransfer(address _pendingOwner) external onlyOwner { require(_pendingOwner != address(0), "Contract must have an owner."); // we want to ensure that we get a cancelled or finished event for every ownership transfer, so if a transfer is in progres we first cancel it if (pendingOwner != address(0)) { cancelOwnershipTransfer(); } pendingOwner = _pendingOwner; emit OwnershipTransferStarted(owner, pendingOwner); } /// @notice cancel an in progress ownership transfer. /// @dev cancellation should not be depended on to cancel a transfer to a malicious address. it's intended purpose is only to cancel transfer to an address that is unable or unwilling to accept the transfer function cancelOwnershipTransfer() public onlyOwner { require(pendingOwner != address(0), "There is no pending transfer to be cancelled."); address _pendingOwner = pendingOwner; pendingOwner = address(0); emit OwnershipTransferCancelled(owner, _pendingOwner); } /// @notice called by the pending owner as part of the two-step ownership transfer process to accept ownership of the contract. function acceptOwnership() external { require(msg.sender == pendingOwner, "Only the pending owner can call this method."); address _oldOwner = owner; owner = pendingOwner; pendingOwner = address(0); emit OwnershipTransferFinished(_oldOwner, owner); } } /// @notice a smart wallet that is secured against loss of keys by way of backup keys that can be used to recover access with a time delay. contract RecoverableWallet is Ownable, Erc777TokensRecipient { event RecoveryAddressAdded(address indexed newRecoverer, uint16 recoveryDelayInDays); event RecoveryAddressRemoved(address indexed oldRecoverer); event RecoveryStarted(address indexed newOwner); event RecoveryCancelled(address indexed oldRecoverer); event RecoveryFinished(address indexed newPendingOwner); /// @notice a collection of accounts that are able to recover control of this wallet, mapped to the number of days it takes for each to complete a recovery. /// @dev the recovery days are also used as a recovery priority, so a recovery address with a lower number of days has a higher recovery priority and can override a lower-priority recovery in progress. mapping(address => uint16) public recoveryDelaysInDays; address public activeRecoveryAddress; uint256 public activeRecoveryEndTime = uint256(-1); /// @notice the modified function can only be called when the wallet is undergoing recovery. modifier onlyDuringRecovery() { require(activeRecoveryAddress != address(0), "This method can only be called during a recovery."); _; } /// @notice the modified function can only be called when the wallet is not undergoing recovery. modifier onlyOutsideRecovery() { require(activeRecoveryAddress == address(0), "This method cannot be called during a recovery."); _; } constructor(address _initialOwner) Ownable(_initialOwner) public { } /// @notice accept ETH transfers into this contract function () external payable { } /// @notice add a new recovery address to the wallet with the specified number of day delay /// @param _newRecoveryAddress the address to be added /// @param _recoveryDelayInDays the number of days delay between when `_newRecoveryAddress` can initiate a recovery and when it can complete the recovery function addRecoveryAddress(address _newRecoveryAddress, uint16 _recoveryDelayInDays) external onlyOwner onlyOutsideRecovery { require(_newRecoveryAddress != address(0), "Recovery address must be supplied."); require(_recoveryDelayInDays > 0, "Recovery delay must be at least 1 day."); recoveryDelaysInDays[_newRecoveryAddress] = _recoveryDelayInDays; emit RecoveryAddressAdded(_newRecoveryAddress, _recoveryDelayInDays); } /// @notice removes a recovery address from the collection, preventing it from being able to issue recovery operations in the future /// @param _oldRecoveryAddress the address to remove from the recovery addresses collection function removeRecoveryAddress(address _oldRecoveryAddress) public onlyOwner onlyOutsideRecovery { require(_oldRecoveryAddress != address(0), "Recovery address must be supplied."); recoveryDelaysInDays[_oldRecoveryAddress] = 0; emit RecoveryAddressRemoved(_oldRecoveryAddress); } /// @notice starts the recovery process. must be called by a previously registered recovery address. recovery will complete in a number of days dependent on the address that initiated the recovery function startRecovery() external { uint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays[msg.sender]; require(_proposedRecoveryDelayInDays != 0, "Only designated recovery addresseses can initiate the recovery process."); bool _inRecovery = activeRecoveryAddress != address(0); if (_inRecovery) { // NOTE: the delay for a particular recovery address cannot be changed during recovery nor can addresses be removed during recovery, so we can rely on this being != 0 uint16 _activeRecoveryDelayInDays = recoveryDelaysInDays[activeRecoveryAddress]; require(_proposedRecoveryDelayInDays < _activeRecoveryDelayInDays, "Recovery is already under way and new recovery doesn't have a higher priority."); emit RecoveryCancelled(activeRecoveryAddress); } activeRecoveryAddress = msg.sender; activeRecoveryEndTime = block.timestamp + _proposedRecoveryDelayInDays * 1 days; emit RecoveryStarted(msg.sender); } /// @notice cancels an active recovery. can only be called by the current contract owner. used to cancel a recovery in case the owner key is found /// @dev cancellation is only reliable if the recovery time has not elapsed function cancelRecovery() public onlyOwner onlyDuringRecovery { address _recoveryAddress = activeRecoveryAddress; resetRecovery(); emit RecoveryCancelled(_recoveryAddress); } /// @notice cancels an active recovery and removes the recovery address from the recoverer collection. used when a recovery key becomes compromised and attempts to initiate a recovery function cancelRecoveryAndRemoveRecoveryAddress() external onlyOwner onlyDuringRecovery { address _recoveryAddress = activeRecoveryAddress; cancelRecovery(); removeRecoveryAddress(_recoveryAddress); } /// @notice finishes the recovery process after the necessary delay has elapsed. callable by anyone in case the keys controlling the active recovery address have been lost, since once this is called a new recovery (with a potentially lower recovery priority) can begin. function finishRecovery() external onlyDuringRecovery { require(block.timestamp > activeRecoveryEndTime, "You must wait until the recovery delay is over before finishing the recovery."); address _oldOwner = owner; owner = activeRecoveryAddress; resetRecovery(); emit RecoveryFinished(pendingOwner); emit OwnershipTransferStarted(_oldOwner, owner); emit OwnershipTransferFinished(_oldOwner, owner); } /// @notice deploy a contract from this contract. /// @dev uses create2, so the address of the deployed contract will be deterministic /// @param _value the amount of ETH that should be supplied to the contract creation call /// @param _data the deployment bytecode to execute /// @param _salt the salt used for deterministic contract creation. see documentation at https://eips.ethereum.org/EIPS/eip-1014 for details on how the address is computed function deploy(uint256 _value, bytes calldata _data, uint256 _salt) external payable onlyOwner onlyOutsideRecovery returns (address) { require(address(this).balance >= _value, "Wallet does not have enough funds available to deploy the contract."); require(_data.length != 0, "Contract deployment must contain bytecode to deploy."); bytes memory _data2 = _data; address newContract; /* solium-disable-next-line */ assembly { newContract := create2(_value, add(_data2, 32), mload(_data2), _salt) } require(newContract != address(0), "Contract creation returned address 0, indicating failure."); return newContract; } /// @notice executes an arbitrary contract call by this wallet. allows the wallet to send ETH, transfer tokens, use dapps, etc. /// @param _to contract address to call or send to /// @param _value the amount of ETH to attach to the call /// @param _data the calldata to supply to `_to` /// @dev `_data` is of the same form used to call a contract from the JSON-RPC API, so for Solidity contract calls it is the target function hash followed by the ABI encoded parameters for that function function execute(address payable _to, uint256 _value, bytes calldata _data) external payable onlyOwner onlyOutsideRecovery returns (bytes memory) { require(_to != address(0), "Transaction execution must contain a destination. If you meant to deploy a contract, use deploy instead."); require(address(this).balance >= _value, "Wallet does not have enough funds available to execute the desired transaction."); (bool _success, bytes memory _result) = _to.call.value(_value)(_data); require(_success, "Contract execution failed."); return _result; } function resetRecovery() private { activeRecoveryAddress = address(0); activeRecoveryEndTime = uint256(-1); } } /// @notice A factory for creating new recoverable wallets. this is useful because an event is fired anytime a wallet is created with this factory, so we can track all wallets created by this by monitoring contract events contract RecoverableWalletFactory { event WalletCreated(address indexed owner, RecoverableWallet indexed wallet); /// @notice creates a new recoverable wallet that is initially owned by the caller function createWallet() external returns (RecoverableWallet) { RecoverableWallet wallet = new RecoverableWallet(msg.sender); emit WalletCreated(msg.sender, wallet); return wallet; } /// @notice this function makes it so one can easily identify whether this contract has been deployed or not. deployment of this factory is done deterministically, so it will live at a well known address on every chain but the user may need to check whether or not this contract has been deployed yet on a given chain function exists() external pure returns (bytes32) { return 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef; } }
called when someone attempts to transfer ERC-777 tokens to this address. If this function were to throw or doesn't exist, then the token transfer would fail.
function tokensReceived(address, address, address, uint256, bytes calldata, bytes calldata) external { }
2,501,227
// SPDX-License-Identifier: MIT pragma solidity =0.8.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "./interfaces/IMintableERC721.sol"; /** * @title Mintable Sale * * @notice Mintable Sale sales fixed amount of NFTs (tokens) for a fixed price in a fixed period of time; * it can be used in a 10k sale campaign and the smart contract is generic and * can sell any type of mintable NFT (see MintableERC721 interface) * * @dev Technically, all the "fixed" parameters can be changed on the go after smart contract is deployed * and operational, but this ability is reserved for quick fix-like adjustments, and to provide * an ability to restart and run a similar sale after the previous one ends * * @dev When buying a token from this smart contract, next token is minted to the recipient * * @dev Supports functionality to limit amount of tokens that can be minted to each address * * @dev Deployment and setup: * 1. Deploy smart contract, specify smart contract address during the deployment: * - Mintable ER721 deployed instance address * 2. Execute `initialize` function and set up the sale parameters; * sale is not active until it's initialized * */ contract MintableSale is Ownable { /** * @dev Next token ID to mint; * initially this is the first "free" ID which can be minted; * at any point in time this should point to a free, mintable ID * for the token * * @dev `nextId` cannot be zero, we do not ever mint NFTs with zero IDs */ uint256 public nextId = 1; /** * @dev Last token ID to mint; * once `nextId` exceeds `finalId` the sale pauses */ uint256 public finalId; // ----- SLOT.1 (224/256) /** * @notice Price of a single item (token) minted * When buying several tokens at once the price accumulates accordingly, with no discount * * @dev Maximum item price is ~18.44 ETH */ uint64 public itemPrice; /** * @notice Sale start unix timestamp; the sale is active after the start (inclusive) */ uint32 public saleStart; /** * @notice Sale end unix timestamp; the sale is active before the end (exclusive) */ uint32 public saleEnd; /** * @notice Once set, limits the amount of tokens one can buy in a single transaction; * When unset (zero) the amount of tokens is limited only by block size and * amount of tokens left for sale */ uint32 public batchLimit; /** * @notice Once set, limits the amount of tokens one address can buy for the duration of the sale; * When unset (zero) the amount of tokens is limited only by the amount of tokens left for sale */ uint32 public mintLimit; /** * @notice Counter of the tokens sold (minted) by this sale smart contract */ uint32 public soldCounter; // ----- NON-SLOTTED /** * @dev Mintable ERC721 contract address to mint */ address public immutable tokenContract; // ----- NON-SLOTTED /** * @dev Developer fee */ uint256 public immutable developerFee; // ----- NON-SLOTTED /** * @dev Address of developer to receive withdraw fees */ address public immutable developerAddress; // ----- NON-SLOTTED /** * @dev Number of mints performed by address */ mapping(address => uint32) mints; /** * @dev Smart contract unique identifier, a random number * * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant UID = 0x3f38351a8d513731422d6b231445dccf6ea9ae952d15c73513da3b92754e778f; /** * @dev Fired in initialize() * * @param _by an address which executed the initialization * @param _itemPrice price of one token created * @param _nextId next ID of the token to mint * @param _finalId final ID of the token to mint * @param _saleStart start of the sale, unix timestamp * @param _saleEnd end of the sale, unix timestamp * @param _batchLimit how many tokens is allowed to buy in a single transaction */ event Initialized( address indexed _by, uint64 _itemPrice, uint256 _nextId, uint256 _finalId, uint32 _saleStart, uint32 _saleEnd, uint32 _batchLimit, uint32 _limit ); /** * @dev Fired in buy(), buyTo(), buySingle(), and buySingleTo() * * @param _by an address which executed and payed the transaction, probably a buyer * @param _to an address which received token(s) minted * @param _amount number of tokens minted * @param _value ETH amount charged */ event Bought(address indexed _by, address indexed _to, uint32 _amount, uint256 _value); /** * @dev Fired in withdraw() and withdrawTo() * * @param _by an address which executed the withdrawal * @param _to an address which received the ETH withdrawn * @param _value ETH amount withdrawn */ event Withdrawn(address indexed _by, address indexed _to, uint256 _value); /** * @dev Creates/deploys MintableSale and binds it to Mintable ERC721 * smart contract on construction * * @param _tokenContract deployed Mintable ERC721 smart contract; sale will mint ERC721 * tokens of that type to the recipient */ constructor(address _tokenContract, uint256 _developerFee, address _developerAddress) { // verify the input is set require(_tokenContract != address(0), "token contract is not set"); // verify that developer address is correct require(_developerAddress != address(0), "developer address is not set"); // verify input is valid smart contract of the expected interfaces require( IERC165(_tokenContract).supportsInterface(type(IMintableERC721).interfaceId) && IERC165(_tokenContract).supportsInterface(type(IMintableERC721).interfaceId), "unexpected token contract type" ); // assign the addresses tokenContract = _tokenContract; // assign the developer fee developerFee = _developerFee; // assign the developer address developerAddress = _developerAddress; } /** * @notice Number of tokens left on sale * * @dev Doesn't take into account if sale is active or not, * if `nextId - finalId < 1` returns zero * * @return number of tokens left on sale */ function itemsOnSale() public view returns(uint256) { // calculate items left on sale, taking into account that // finalId is on sale (inclusive bound) return finalId >= nextId? finalId + 1 - nextId: 0; } /** * @notice Number of tokens available on sale * * @dev Takes into account if sale is active or not, doesn't throw, * returns zero if sale is inactive * * @return number of tokens available on sale */ function itemsAvailable() public view returns(uint256) { // delegate to itemsOnSale() if sale is active, return zero otherwise return isActive()? itemsOnSale(): 0; } /** * @notice Active sale is an operational sale capable of minting and selling tokens * * @dev The sale is active when all the requirements below are met: * 1. Price is set (`itemPrice` is not zero) * 2. `finalId` is not reached (`nextId <= finalId`) * 3. current timestamp is between `saleStart` (inclusive) and `saleEnd` (exclusive) * * @dev Function is marked as virtual to be overridden in the helper test smart contract (mock) * in order to test how it affects the sale process * * @return true if sale is active (operational) and can sell tokens, false otherwise */ function isActive() public view virtual returns(bool) { // evaluate sale state based on the internal state variables and return return itemPrice > 0 && nextId <= finalId && saleStart <= block.timestamp && saleEnd > block.timestamp; } /** * @dev Restricted access function to set up sale parameters, all at once, * or any subset of them * * @dev To skip parameter initialization, set it to `-1`, * that is a maximum value for unsigned integer of the corresponding type; * `_aliSource` and `_aliValue` must both be either set or skipped * * @dev Example: following initialization will update only _itemPrice and _batchLimit, * leaving the rest of the fields unchanged * initialize( * 100000000000000000, * 0xFFFFFFFF, * 0xFFFFFFFF, * 0xFFFFFFFF, * 0xFFFFFFFF, * 10, * 0xFFFFFFFF * ) * * @dev Requires next ID to be greater than zero (strict): `_nextId > 0` * * @dev Requires transaction sender to have `ROLE_SALE_MANAGER` role * * @param _itemPrice price of one token created; * setting the price to zero deactivates the sale * @param _nextId next ID of the token to mint, will be increased * in smart contract storage after every successful buy * @param _finalId final ID of the token to mint; sale is capable of producing * `_finalId - _nextId + 1` tokens * @param _saleStart start of the sale, unix timestamp * @param _saleEnd end of the sale, unix timestamp; sale is active only * when current time is within _saleStart (inclusive) and _saleEnd (exclusive) * @param _batchLimit how many tokens is allowed to buy in a single transaction, * set to zero to disable the limit * @param _mintLimit how many tokens is allowed to buy for the duration of the sale, * set to zero to disable the limit */ function initialize( uint64 _itemPrice, // <<<--- keep type in sync with the body type(uint64).max !!! uint256 _nextId, // <<<--- keep type in sync with the body type(uint256).max !!! uint256 _finalId, // <<<--- keep type in sync with the body type(uint256).max !!! uint32 _saleStart, // <<<--- keep type in sync with the body type(uint32).max !!! uint32 _saleEnd, // <<<--- keep type in sync with the body type(uint32).max !!! uint32 _batchLimit, // <<<--- keep type in sync with the body type(uint32).max !!! uint32 _mintLimit // <<<--- keep type in sync with the body type(uint32).max !!! ) public onlyOwner { // verify the inputs require(_nextId > 0, "zero nextId"); // no need to verify extra parameters - "incorrect" values will deactivate the sale // initialize contract state based on the values supplied // take into account our convention that value `-1` means "do not set" // 0xFFFFFFFFFFFFFFFF, 64 bits if(_itemPrice != type(uint64).max) { itemPrice = _itemPrice; } // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 256 bits if(_nextId != type(uint256).max) { nextId = _nextId; } // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 256 bits if(_finalId != type(uint256).max) { finalId = _finalId; } // 0xFFFFFFFF, 32 bits if(_saleStart != type(uint32).max) { saleStart = _saleStart; } // 0xFFFFFFFF, 32 bits if(_saleEnd != type(uint32).max) { saleEnd = _saleEnd; } // 0xFFFFFFFF, 32 bits if(_batchLimit != type(uint32).max) { batchLimit = _batchLimit; } // 0xFFFFFFFF, 32 bits if(_mintLimit != type(uint32).max) { mintLimit = _mintLimit; } // emit an event - read values from the storage since not all of them might be set emit Initialized( msg.sender, itemPrice, nextId, finalId, saleStart, saleEnd, batchLimit, mintLimit ); } /** * @notice Buys several (at least two) tokens in a batch. * Accepts ETH as payment and mints a token * * @param _amount amount of tokens to create, two or more */ function buy(uint32 _amount) public payable { // delegate to `buyTo` with the transaction sender set to be a recipient buyTo(msg.sender, _amount); } /** * @notice Buys several (at least two) tokens in a batch to an address specified. * Accepts ETH as payment and mints tokens * * @param _to address to mint tokens to * @param _amount amount of tokens to create, two or more */ function buyTo(address _to, uint32 _amount) public payable { // verify the inputs require(_to != address(0), "recipient not set"); require(_amount > 1 && (batchLimit == 0 || _amount <= batchLimit), "incorrect amount"); // verify mint limit if(mintLimit != 0) { require(mints[msg.sender] + _amount <= mintLimit, "mint limit reached"); } // verify there is enough items available to buy the amount // verifies sale is in active state under the hood require(itemsAvailable() >= _amount, "inactive sale or not enough items available"); // calculate the total price required and validate the transaction value uint256 totalPrice = uint256(itemPrice) * _amount; require(msg.value >= totalPrice, "not enough funds"); // mint token to to the recipient IMintableERC721(tokenContract).mintBatch(_to, nextId, _amount); // increment `nextId` nextId += _amount; // increment `soldCounter` soldCounter += _amount; // increment sender mints mints[msg.sender] += _amount; // if ETH amount supplied exceeds the price if(msg.value > totalPrice) { // send excess amount back to sender payable(msg.sender).transfer(msg.value - totalPrice); } // emit en event emit Bought(msg.sender, _to, _amount, totalPrice); } /** * @notice Buys single token. * Accepts ETH as payment and mints a token */ function buySingle() public payable { // delegate to `buySingleTo` with the transaction sender set to be a recipient buySingleTo(msg.sender); } /** * @notice Buys single token to an address specified. * Accepts ETH as payment and mints a token * * @param _to address to mint token to */ function buySingleTo(address _to) public payable { // verify the inputs and transaction value require(_to != address(0), "recipient not set"); require(msg.value >= itemPrice, "not enough funds"); // verify mint limit if(mintLimit != 0) { require(mints[msg.sender] + 1 <= mintLimit, "mint limit reached"); } // verify sale is in active state require(isActive(), "inactive sale"); // mint token to the recipient IMintableERC721(tokenContract).mint(_to, nextId); // increment `nextId` nextId++; // increment `soldCounter` soldCounter++; // increment sender mints mints[msg.sender]++; // if ETH amount supplied exceeds the price if(msg.value > itemPrice) { // send excess amount back to sender payable(msg.sender).transfer(msg.value - itemPrice); } // emit en event emit Bought(msg.sender, _to, 1, itemPrice); } /** * @dev Restricted access function to withdraw ETH on the contract balance, * sends ETH back to transaction sender */ function withdraw() public { // delegate to `withdrawTo` withdrawTo(msg.sender); } /** * @dev Restricted access function to withdraw ETH on the contract balance, * sends ETH to the address specified * * @param _to an address to send ETH to */ function withdrawTo(address _to) public onlyOwner { // verify withdrawal address is set require(_to != address(0), "address not set"); // ETH value to send uint256 _value = address(this).balance; uint256 computedDevFee = _value * developerFee / 100; _value -= computedDevFee; // verify sale balance is positive (non-zero) require(_value > 0, "zero balance"); // send the entire balance to the transaction sender payable(_to).transfer(_value); payable(developerAddress).transfer(computedDevFee); // emit en event emit Withdrawn(msg.sender, _to, _value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity 0.8.12; interface IMintableERC721 { /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * * @param _tokenId ID of the token to query existence for * @return whether the token exists (true - exists, false - doesn't exist) */ function exists(uint256 _tokenId) external view returns(bool); /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMint` instead of `mint`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMintBatch` instead of `mintBatch`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint tokens to * @param _tokenId ID of the first token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function mintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param _data additional data with no specified format, sent in call to `_to` */ function safeMint(address _to, uint256 _tokenId, bytes memory _data) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId * @param _data additional data with no specified format, sent in call to `_to` */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
Restricted access function to set up sale parameters, all at once, or any subset of them To skip parameter initialization, set it to `-1`, that is a maximum value for unsigned integer of the corresponding type; `_aliSource` and `_aliValue` must both be either set or skipped Example: following initialization will update only _itemPrice and _batchLimit, leaving the rest of the fields unchanged initialize( 100000000000000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 10, 0xFFFFFFFF ) Requires next ID to be greater than zero (strict): `_nextId > 0` Requires transaction sender to have `ROLE_SALE_MANAGER` role _itemPrice price of one token created; setting the price to zero deactivates the sale _nextId next ID of the token to mint, will be increased in smart contract storage after every successful buy _finalId final ID of the token to mint; sale is capable of producing `_finalId - _nextId + 1` tokens _saleStart start of the sale, unix timestamp _saleEnd end of the sale, unix timestamp; sale is active only when current time is within _saleStart (inclusive) and _saleEnd (exclusive) _batchLimit how many tokens is allowed to buy in a single transaction, set to zero to disable the limit _mintLimit how many tokens is allowed to buy for the duration of the sale, set to zero to disable the limit/ verify the inputs no need to verify extra parameters - "incorrect" values will deactivate the sale initialize contract state based on the values supplied take into account our convention that value `-1` means "do not set" 0xFFFFFFFFFFFFFFFF, 64 bits 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 256 bits 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, 256 bits 0xFFFFFFFF, 32 bits 0xFFFFFFFF, 32 bits 0xFFFFFFFF, 32 bits 0xFFFFFFFF, 32 bits
function initialize( ) public onlyOwner { require(_nextId > 0, "zero nextId"); if(_itemPrice != type(uint64).max) { itemPrice = _itemPrice; } if(_nextId != type(uint256).max) { nextId = _nextId; } if(_finalId != type(uint256).max) { finalId = _finalId; } if(_saleStart != type(uint32).max) { saleStart = _saleStart; } if(_saleEnd != type(uint32).max) { saleEnd = _saleEnd; } if(_batchLimit != type(uint32).max) { batchLimit = _batchLimit; } if(_mintLimit != type(uint32).max) { mintLimit = _mintLimit; } msg.sender, itemPrice, nextId, finalId, saleStart, saleEnd, batchLimit, mintLimit ); }
191,361
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // int256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(int256 a, int256 b) internal pure returns (int256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns (int256 c) { c = a + b; assert(c >= a); return c; } } // This contract will be used to register nodes. contract Registration { using SafeMath for int256; int private nodesCount; address public owner; mapping(address => bool) public acceptedOracles; mapping(address => FLNode) private flNodes; mapping(int256 => mapping(address => bool)) public resultsReportedForThisNode; event NewOracleToReportResultAdded(address oracleAddress); event AcceptedNodeEvent(address results_reporter, int256 process_id, address node, int256 reputation); event FailedNodeEvent(address results_reporter, int256 process_id, address node, int256 reputation); event WithdrwanNodeEvent(address results_reporter, int256 process_id, address node, int256 reputation); struct FLNode{ int id; int R1; int R2; int R3; int reputation; bool registered; } constructor() public{ nodesCount = 0; owner = msg.sender; } // This function is to add oracles, oracles are responsible for reporting evaluations.. // scores for each node participated function AddOracleToReportResults(address oracleAddress) public{ require(msg.sender == owner, "You are not authorized to add oracles"); require(oracleAddress != owner, "Owner cannot be an oracle"); acceptedOracles[oracleAddress] = true; emit NewOracleToReportResultAdded(oracleAddress); } // This function is used by any node looking forward to register itself. function RegisterNode() public { require(msg.sender != owner, "Owner cannot be a node"); require(flNodes[msg.sender].registered == false, "This address is aleardy registered"); nodesCount.add(1); flNodes[msg.sender] = FLNode(nodesCount, 0,0,0,0, true); } // This function is used to calculate the reputation score. function calculateReputation(address nodeAddress) private view returns(int){ int x = flNodes[nodeAddress].R1.sub(flNodes[nodeAddress].R2); x = x.mul(100); int y = flNodes[nodeAddress].R1.add(flNodes[nodeAddress].R2); y = y.add(flNodes[nodeAddress].R3); int z = x.div(y); return z; } // This function is used by the FL FLEstablishment SC to check the reputation // of each node, this added cost because of smart contract calling // another smart contract is to avoid malicous nodes as much as possible. function VerifyReputation(address nodeAddress, int256 min_reputation) public returns(bool){ require(flNodes[nodeAddress].registered == true, "This node is not registered"); if(flNodes[nodeAddress].reputation >= min_reputation) { flNodes[nodeAddress].R1.add(1); flNodes[nodeAddress].reputation = calculateReputation(nodeAddress); return true; } return false; } function RejectedNode(address nodeAddress, int256 process_id) public { require(acceptedOracles[msg.sender], "You are not authorized to report results" ); require(!resultsReportedForThisNode[process_id][nodeAddress], "Results already reported "); flNodes[nodeAddress].R1.sub(1); flNodes[nodeAddress].R2.add(1); flNodes[nodeAddress].reputation = calculateReputation(nodeAddress); resultsReportedForThisNode[process_id][nodeAddress] = true; emit FailedNodeEvent(msg.sender, process_id, nodeAddress, flNodes[nodeAddress].reputation); } function WithdrawnNode(address nodeAddress, int256 process_id) public { require(acceptedOracles[msg.sender], "You are not authorized to report results" ); require(!resultsReportedForThisNode[process_id][nodeAddress], "Results already reported "); flNodes[nodeAddress].R1.sub(1); flNodes[nodeAddress].R3.add(1); flNodes[nodeAddress].reputation = calculateReputation(nodeAddress); resultsReportedForThisNode[process_id][nodeAddress] = true; emit WithdrwanNodeEvent(msg.sender, process_id, nodeAddress, flNodes[nodeAddress].reputation); } } contract FLEstablishment{ using SafeMath for int256; Registration public registration; int256 private process_count; mapping(int256 => FLProcess) public fl_processes; mapping(int256 => bool) public participationOpen; mapping(int256 => bool) public votingClosed; mapping(int => bool) uploadUpdatesClosed; mapping(int256 => bool) evaluationClosed; mapping(int256 => mapping(address => bool)) public participants; mapping(int256 => int256) public participants_count; mapping(int256 => mapping(address => InitialModelProposal)) public initialModelProposals; mapping(int256 => mapping(address => bool)) hasVotedForInitialModel; mapping(int256 => InitialModelProposal) winingInitialModelProposal; event FLProcessRegistered(address owner, int256 process_id, string name); event Participated(address nodeAddress, int256 process_id); event ParticipationEnded(address process_owner, int256 process_id); event InitialModelProposed(address proposal_owner, int256 process_id); event VotedForInitialModel(address voter, address proposal_owner, int256 process_id); event VotingForInitialModelEnded(int256 process_id, int256 count, string cfl, string cfh); event ModelUpdatesUpload(address nodeAddress, int256 process_id, string ref, string hash); event ModelUpdatesUploadPeriodEnded(address process_owner, int process_id); event EvaluationUploaded(address process_owner, int process_id, string evaluation_files); event EvaluationEnded(address process_owner, int256 process_id); event FinalModelUploaded(address owner, int process_id, string final_model_files); struct FLProcess{ int256 id; address owner; int256 min_reputation; string name; string initial_configuration_files_link; string initial_configuration_files_hash; bool registered; } struct InitialModelProposal{ string configuration_files_link; string configuration_files_hash; int256 count; } constructor(address registration_address) public{ registration = Registration(registration_address); process_count = 0; } // This function used to create a new FL Process, this node is called the master function StartNewFL(int256 minReputation, string memory name, string memory icfl, string memory icfh) public{ require(registration.VerifyReputation(msg.sender,0) == true, "You are not registered node"); fl_processes[process_count] = FLProcess(process_count, msg.sender,minReputation,name, icfl, icfh, true); participationOpen[process_count] = true; participants[process_count][msg.sender] = true; participants_count[process_count].add(1); initialModelProposals[process_count][msg.sender] = InitialModelProposal(icfl, icfh, 0); emit FLProcessRegistered(msg.sender, process_count, name); process_count.add(1); } // This function used to participate in some FL Process function Participate(int256 process_id) public{ require(fl_processes[process_id].registered, "The FL Process does not exist"); require(participants[process_id][msg.sender] == false, "Your are registered in this FL Process"); require(participationOpen[process_id], "The participation period is over"); require(registration.VerifyReputation(msg.sender, fl_processes[process_id].min_reputation), "Your reputation is lower than required"); participants[process_id][msg.sender] = true; participants_count[process_id].add(1); emit Participated(msg.sender, process_id); } // This function is called by the master to end the participation period function EndParticipation(int256 process_id) public{ require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); participationOpen[process_id] = false; emit ParticipationEnded(msg.sender, process_id); } // This function is used to propose new initial model function Propose(int256 process_id, string memory cfl, string memory cfh) public{ require(participants[process_id][msg.sender] == true, "Your are not registered in this FL Process"); require(participationOpen[process_id] == false, "Participation period is not over yet"); initialModelProposals[process_id][msg.sender] = InitialModelProposal(cfl, cfh, 0); emit InitialModelProposed(msg.sender, process_id); } // This is a voting function, used to vote for desired intial model configurations function Vote(int256 process_id, address proposal_owner) public{ require(votingClosed[process_id] == false, "Voting period is over"); require(participants[process_id][msg.sender] == true, "You are not registered in this FL Process"); require(hasVotedForInitialModel[process_id][msg.sender] == false, "You have voted before"); initialModelProposals[process_id][proposal_owner].count.add(1); if(initialModelProposals[process_id][proposal_owner].count > winingInitialModelProposal[process_id].count){ winingInitialModelProposal[process_id] = initialModelProposals[process_id][proposal_owner]; } hasVotedForInitialModel[process_id][msg.sender] = true; emit VotedForInitialModel(msg.sender, proposal_owner, process_id); } // This function is called by the master to end the voting period function EndVotingForInitialModel(int256 process_id) public{ require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); votingClosed[process_id] = true; emit VotingForInitialModelEnded(process_id,winingInitialModelProposal[process_id].count, winingInitialModelProposal[process_id].configuration_files_link, winingInitialModelProposal[process_id].configuration_files_hash); } // This function is used to annouce the model updates uploaded by some participant function UploadUpdates(int256 process_id, string memory ref, string memory hash) public{ require(uploadUpdatesClosed[process_id] == false, "Period to upload updates ended"); emit ModelUpdatesUpload(msg.sender, process_id, ref, hash); } // This function is called by the master to end the period for Uploading Model Updates function EndModelUpdatesUpload(int process_id) public { require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); uploadUpdatesClosed[process_id] = true; emit ModelUpdatesUploadPeriodEnded(msg.sender, process_id); } // This function is used to annouce the evaluation uploaded by some participant // Oracle will keep listening for these event, download the evaluations // and aggregate them to form the final evaluation score for each node. function UploadEvaluation(int process_id, string memory ref) public{ require(evaluationClosed[process_id] == false, "Period to upload evaluations ended"); emit EvaluationUploaded(msg.sender, process_id, ref); } // This function is called by the master to end the period for Uploading evaluations // Oracles will not accept any further evaluations after this event. function EndEvaluation(int process_id) public { require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); evaluationClosed[process_id] = true; emit EvaluationEnded(msg.sender, process_id); } // This function is used to annouce the final global model. function UploadFinalModel(int process_id, string memory ref) public{ require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); emit FinalModelUploaded(msg.sender, process_id, ref); } }
This function is called by the master to end the voting period
function EndVotingForInitialModel(int256 process_id) public{ require(fl_processes[process_id].owner == msg.sender, "You are not the owner of this FL Process"); votingClosed[process_id] = true; emit VotingForInitialModelEnded(process_id,winingInitialModelProposal[process_id].count, winingInitialModelProposal[process_id].configuration_files_link, winingInitialModelProposal[process_id].configuration_files_hash); }
15,882,967
./full_match/1/0x4722B25813593FF79f34A4ff4375B8e23095c708/sources/src/PriceBulletin.sol
Same as `updateBulletin()`, but logging a claim for rewards. Rewards earned by calling this method can be claimed at a later point using the `claimRewards()` method. callData encoded RounData with v,r,s signature values Requirements: - Must revert if no reward token or amount are set/
function updateBulletinWithRewardLog(bytes memory callData) public returns (bool success) { if (updateBulletin(callData)) { _logEarnedReward(msg.sender, rewardToken, rewardAmount); success = true; } }
9,643,142
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(_b > 0); uint256 c = _a / _b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); return _a - _b; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } // allows execution by the owner only modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public onlyNewOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* ERC20 Token interface */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function allowance(address owner, address spender) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function sendwithgas(address _from, address _to, uint256 _value, uint256 _fee) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract FIITLAB is ERC20, Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 internal initialSupply; uint256 internal totalSupply_; mapping(address => uint256) internal balances; mapping(address => bool) public frozen; mapping(address => mapping(address => uint256)) internal allowed; event Burn(address indexed owner, uint256 value); event Freeze(address indexed holder); event Unfreeze(address indexed holder); modifier notFrozen(address _holder) { require(!frozen[_holder]); _; } constructor() public { name = "FIITLAB"; symbol = "FIIT"; decimals = 18; initialSupply = 1000000000 * (10 ** uint256(decimals)); totalSupply_ = 1000000000 * (10 ** uint256(decimals)); balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); } function () public payable { revert(); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified addresses * @param _from The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint _value) internal { 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); emit Transfer(_from, _to, _value); } /** * @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 notFrozen(msg.sender) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _holder The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _holder) public view returns (uint256 balance) { return balances[_holder]; } /** * ERC20 Token Transfer */ function sendwithgas(address _from, address _to, uint256 _value, uint256 _fee) public onlyOwner notFrozen(_from) returns (bool) { uint256 _total; _total = _value.add(_fee); require(!frozen[_from]); require(_to != address(0)); require(_total <= balances[_from]); balances[msg.sender] = balances[msg.sender].add(_fee); balances[_from] = balances[_from].sub(_total); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); emit Transfer(_from, msg.sender, _fee); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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 notFrozen(_from) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); _transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to _spender 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; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an _holder allowed to a spender. * @param _holder 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 _holder, address _spender) public view returns (uint256) { return allowed[_holder][_spender]; } /** * Freeze Account. */ function freezeAccount(address _holder) public onlyOwner returns (bool) { require(!frozen[_holder]); frozen[_holder] = true; emit Freeze(_holder); return true; } /** * Unfreeze Account. */ function unfreezeAccount(address _holder) public onlyOwner returns (bool) { require(frozen[_holder]); frozen[_holder] = false; emit Unfreeze(_holder); return true; } /** * Token Burn. */ function burn(uint256 _value) public onlyOwner returns (bool) { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); return true; } function burn_address(address _target) public onlyOwner returns (bool){ require(_target != address(0)); uint256 _targetValue = balances[_target]; balances[_target] = 0; totalSupply_ = totalSupply_.sub(_targetValue); address burner = msg.sender; emit Burn(burner, _targetValue); return true; } /** * @dev Internal function to determine if an address is a contract * @param addr The address being queried * @return True if `_addr` is a contract */ function isContract(address addr) internal view returns (bool) { uint size; assembly{size := extcodesize(addr)} return size > 0; } }
Approve the passed address to _spender 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: _spender The address which will spend the funds. _value The amount of tokens to be spent./
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
95,515
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "../../access/IOwnable.sol"; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; /** * @dev Minimal implementation https://eips.ethereum.org/EIPS/eip-721[ERC721] * Non-Fungible Token Standard. * * ███╗ ███╗██╗███╗ ██╗███████╗████████╗ * ████╗ ████║██║████╗ ██║██╔════╝╚══██╔══╝ * ██╔████╔██║██║██╔██╗ ██║█████╗ ██║ * ██║╚██╔╝██║██║██║╚██╗██║██╔══╝ ██║ * ██║ ╚═╝ ██║██║██║ ╚████║██║ ██║ * ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ * */ contract MiNFT is Initializable, IERC165, IERC721, IERC721Metadata, IOwnable { // Contract & token owner address public override owner; // Token name string public override name; // Token name string public override symbol; // Optional base URI string public baseURI; // Total supply of tokens uint16 public totalSupply; // Mapping of tokenIds to token metadata mapping(uint16 => string) private _mintedTokens; // ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ ██████╗ ██████╗ // ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗ // ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ ██║ ██║██████╔╝ // ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ ██║ ██║██╔══██╗ // ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║ // ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() initializer { owner = msg.sender; } function initialize(string memory name_, string memory symbol_) public initializer { owner = msg.sender; name = name_; symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IOwnable).interfaceId ; } modifier onlyOwner() { require(msg.sender == owner, 'X'); _; } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ /** * @dev Mints `tokenId` and transfers it to `owner()`. * * Emits a {Transfer} event. */ function mint(uint16 tokenId, string memory metadataURI) public onlyOwner { require(!_exists(tokenId), '?'); require(bytes(metadataURI).length > 0, '0'); _mintedTokens[tokenId] = metadataURI; totalSupply += 1; emit Transfer(address(0), owner, tokenId); } /** * @dev Destroys `tokenId`. * * Emits a {Transfer} event. */ function burn(uint16 tokenId) public onlyOwner { require(_exists(tokenId), '?'); delete _mintedTokens[tokenId]; totalSupply -= 1; emit Transfer(owner, address(0), tokenId); } // ███╗ ███╗███████╗████████╗ █████╗ ██████╗ █████╗ ████████╗ █████╗ // ████╗ ████║██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗ // ██╔████╔██║█████╗ ██║ ███████║██║ ██║███████║ ██║ ███████║ // ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██╔══██║ ██║ ██╔══██║ // ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║██████╔╝██║ ██║ ██║ ██║ ██║ // ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), '?'); string memory metadataURI; string memory _tokenURI = _mintedTokens[uint16(tokenId)]; if (bytes(baseURI).length == 0) { metadataURI = _tokenURI; } else { metadataURI = string(abi.encodePacked(baseURI, _tokenURI)); } return metadataURI; } /** * @dev Updates a token's metadata URI. */ function setTokenURI(uint16 tokenId, string memory metadataURI) public onlyOwner { require(_exists(tokenId), '?'); _mintedTokens[tokenId] = metadataURI; } /** * @dev Updates contract base URI. */ function setBaseURI(string memory newURI) public onlyOwner { baseURI = newURI; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address wallet) public view virtual override returns (uint256) { require(wallet != address(0)); return wallet == owner ? totalSupply : 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId)); return owner; } /** * @dev Returns whether `tokenId` exists. * * Tokens start existing when they are minted (`mint`), * and stop existing when they are burned (`burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return bytes(_mintedTokens[uint16(tokenId)]).length > 0; } // ██████╗ ███████╗ █████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██╗ ██╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔═══██╗████╗ ██║██║ ╚██╗ ██╔╝ // ██████╔╝█████╗ ███████║██║ ██║█████╗██║ ██║██╔██╗ ██║██║ ╚████╔╝ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║╚════╝██║ ██║██║╚██╗██║██║ ╚██╔╝ // ██║ ██║███████╗██║ ██║██████╔╝ ╚██████╔╝██║ ╚████║███████╗██║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚═╝ // // https://eips.ethereum.org/EIPS/eip-721 Read only NFT registry. /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256) public view virtual override returns (address) { return address(0); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address, address) public view virtual override returns (bool) { return false; } /** * @dev See {IERC721-approve}. */ function approve(address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address, bool) public virtual override { revert('X'); } /** * @dev See {IERC721-setApprovalForAll}. */ function transferFrom(address, address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address, address, uint256) public virtual override { revert('X'); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address, address, uint256, bytes memory) public virtual override { revert('X'); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom(address, address, uint256) public virtual override { revert('X'); }
13,103,935
pragma solidity >=0.4.24; contract GlobalVariables { string public lastCaller = "not-set"; // Demonstrates the use of the ether subdenominations function etherUnitsTest() public pure returns (bool) { // True bool value = (1 ether == 1000 finney); return value; } // Demonstrates the use of the time units function timeUnits() public view returns (uint256) { uint256 timeNow = now; //storing current time using now //returns block time in seconds since 1970 if (timeNow == 1000 hours) { // converting 1000 literal to days, using the suffix days return timeNow; } } // Demonstrates the use of block object function getBlockInformation() public view returns ( uint256 number, bytes32 hash, address coinbase, uint256 difficulty ) { number = block.number; // Previous block hash = blockhash(number - 1); // -1 because excluding current...same as block.blockhash() // Current block coinbase = block.coinbase; difficulty = block.difficulty; } // Demonstrates the use of the msg object function getMsgInformation() public view returns ( bytes memory data, bytes4 sig, address sender ) { data = msg.data; sig = msg.sig; sender = msg.sender; } //Global variables for ethereum environment //tx //tx.origin; // the ethereum address that sends the transaction //msg msg.value // amount of ether send to address 1wei = 10^(-18) ether msg.sender ;// these are addresses for every sender withi9n smart contract. and // tx.origin is just the origin address if inheritance is there //block block.timestamp;// the time when block is created or we can use now keywork }
Demonstrates the use of the msg object
function getMsgInformation() public view returns ( bytes memory data, bytes4 sig, address sender ) { data = msg.data; sig = msg.sig; sender = msg.sender; }
12,988,157
pragma solidity ^0.4.20; contract GenesisProtected { modifier addrNotNull(address _address) { require(_address != address(0)); _; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/ownership/Ownable.sol // Changed function name: transferOwnership -> setOwner. // Added inheritance from GenesisProtected (address != 0x0). // setOwner refactored for emitting after owner replacing. // ---------------------------------------------------------------------------- /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is GenesisProtected { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a _new. * @param a The address to transfer ownership to. */ function setOwner(address a) external onlyOwner addrNotNull(a) { owner = a; emit OwnershipReplaced(msg.sender, a); } event OwnershipReplaced( address indexed previousOwner, address indexed newOwner ); } contract Enums { // Type for mapping uint (index) => name for baskets types described in WP enum BasketType { unknown, // 0 unknown team, // 1 Team foundation, // 2 Foundation arr, // 3 Advertisement, Referral program, Reward advisors, // 4 Advisors bounty, // 5 Bounty referral, // 6 Referral referrer // 7 Referrer } } contract WPTokensBaskets is Ownable, Enums { // This mapping holds all accounts ever used as baskets forever mapping (address => BasketType) internal types; // Baskets for tokens address public team; address public foundation; address public arr; address public advisors; address public bounty; // Public constructor function WPTokensBaskets( address _team, address _foundation, address _arr, address _advisors, address _bounty ) public { setTeam(_team); setFoundation(_foundation); setARR(_arr); setAdvisors(_advisors); setBounty(_bounty); } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } function typeOf(address a) public view returns (BasketType) { return types[a]; } // Return truth if given address is not registered as token basket. function isUnknown(address a) public view returns (bool) { return types[a] == BasketType.unknown; } function isTeam(address a) public view returns (bool) { return types[a] == BasketType.team; } function isFoundation(address a) public view returns (bool) { return types[a] == BasketType.foundation; } function setTeam(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[team = a] = BasketType.team; } function setFoundation(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[foundation = a] = BasketType.foundation; } function setARR(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[arr = a] = BasketType.arr; } function setAdvisors(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[advisors = a] = BasketType.advisors; } function setBounty(address a) public onlyOwner addrNotNull(a) { require(types[a] == BasketType.unknown); types[bounty = a] = BasketType.bounty; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/math/SafeMath.sol // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is * greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // The original code is taken from: // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); } contract Token is Ownable, ERC20Interface, Enums { using SafeMath for uint; // Token full name string private constant NAME = "EnvisionX EXCHAIN Token"; // Token symbol name string private constant SYMBOL = "EXT"; // Token max fraction, in decimal signs after the point uint8 private constant DECIMALS = 18; // Tokens max supply, in EXTwei uint public constant MAX_SUPPLY = 3000000000 * (10**uint(DECIMALS)); // Tokens balances map mapping(address => uint) internal balances; // Maps with allowed amounts fot TransferFrom mapping (address => mapping (address => uint)) internal allowed; // Total amount of issued tokens, in EXTwei uint internal _totalSupply; // Map with Ether founds amount by address (using when refunds) mapping(address => uint) internal etherFunds; uint internal _earnedFunds; // Map with refunded addreses (Black List) mapping(address => bool) internal refunded; // Address of sale agent (a contract) which can mint new tokens address public mintAgent; // Token transfer allowed only when token minting is finished bool public isMintingFinished = false; // When minting was finished uint public mintingStopDate; // Total amount of tokens minted to team basket, in EXTwei. // This will not include tokens, transferred to team basket // after minting is finished. uint public teamTotal; // Amount of tokens spent by team in first 96 weeks since // minting finish date. Used to calculate team spend // restrictions according to ICO White Paper. uint public spentByTeam; // Address of WPTokensBaskets contract WPTokensBaskets public wpTokensBaskets; // Constructor function Token(WPTokensBaskets baskets) public { wpTokensBaskets = baskets; mintAgent = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } /** ---------------------------------------------------------------------- ERC20 Interface implementation */ // Return token full name function name() public pure returns (string) { return NAME; } // Return token symbol name function symbol() public pure returns (string) { return SYMBOL; } // Return amount of decimals after point function decimals() public pure returns (uint8) { return DECIMALS; } // Return total amount of issued tokens, in EXTwei function totalSupply() public constant returns (uint) { return _totalSupply; } // Return account balance in tokens (in EXTwei) function balanceOf(address _address) public constant returns (uint) { return balances[_address]; } // Transfer tokens to another account function transfer(address to, uint value) public addrNotNull(to) returns (bool) { if (balances[msg.sender] < value) return false; if (isFrozen(wpTokensBaskets.typeOf(msg.sender), value)) return false; balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); saveTeamSpent(msg.sender, value); emit Transfer(msg.sender, to, value); return true; } // Transfer tokens from one account to another, // using permissions defined with approve() method. function transferFrom(address from, address to, uint value) public addrNotNull(to) returns (bool) { if (balances[from] < value) return false; if (allowance(from, msg.sender) < value) return false; if (isFrozen(wpTokensBaskets.typeOf(from), value)) return false; balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); saveTeamSpent(from, value); emit Transfer(from, to, value); return true; } // Allow to transfer given amount of tokens (in EXTwei) // to account which is not owner. function approve(address spender, uint value) public returns (bool) { if (msg.sender == spender) return false; allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // Return amount of tokens (in EXTwei) which allowed to // be transferred by non-owner spender function allowance(address _owner, address spender) public constant returns (uint) { return allowed[_owner][spender]; } /** ---------------------------------------------------------------------- Other methods */ // Return account funds in ether (in wei) function etherFundsOf(address _address) public constant returns (uint) { return etherFunds[_address]; } // Return total amount of funded ether, in wei function earnedFunds() public constant returns (uint) { return _earnedFunds; } // Return true if given address have been refunded function isRefunded(address _address) public view returns (bool) { return refunded[_address]; } // Set new address of sale agent contract. // Will be called for each sale stage: PrivateSale, PreSale, MainSale. function setMintAgent(address a) public onlyOwner addrNotNull(a) { emit MintAgentReplaced(mintAgent, a); mintAgent = a; } // Interface for sale agent contract - mint new tokens function mint(address to, uint256 extAmount, uint256 etherAmount) public { require(!isMintingFinished); require(msg.sender == mintAgent); require(!refunded[to]); _totalSupply = _totalSupply.add(extAmount); require(_totalSupply <= MAX_SUPPLY); balances[to] = balances[to].add(extAmount); if (wpTokensBaskets.isUnknown(to)) { _earnedFunds = _earnedFunds.add(etherAmount); etherFunds[to] = etherFunds[to].add(etherAmount); } else if (wpTokensBaskets.isTeam(to)) { teamTotal = teamTotal.add(extAmount); } emit Mint(to, extAmount); emit Transfer(msg.sender, to, extAmount); } // Destroy minted tokens and refund ether spent by investor. // Used in AML (Anti Money Laundering) workflow. // Will be called only by humans because there is no way // to withdraw crowdfunded ether from Beneficiary account // from context of this account. // Important note: all tokens minted to team, foundation etc. // will NOT be burned, because they in general are spent // during the sale and its too expensive to track all these // transactions. function burnTokensAndRefund(address _address) external payable addrNotNull(_address) onlyOwner() { require(msg.value > 0 && msg.value == etherFunds[_address]); _totalSupply = _totalSupply.sub(balances[_address]); balances[_address] = 0; _earnedFunds = _earnedFunds.sub(msg.value); etherFunds[_address] = 0; refunded[_address] = true; _address.transfer(msg.value); } // Stop tokens minting forever. function finishMinting() external onlyOwner { require(!isMintingFinished); isMintingFinished = true; mintingStopDate = now; emit MintingFinished(); } /** ---------------------------------------------------------------------- Tokens freeze logic, according to ICO White Paper */ // Return truth if given _value amount of tokens (in EXTwei) // cannot be transferred from account due to spend restrictions // defined in ICO White Paper. // !!!Caveat of current implementaion!!! // Say, // 1. There was 100 tokens minted to the team basket; // 2. Minting was finished and 24 weeks elapsed, and now // team can spend up to 25 tokens till next 24 weeks; // 3. Someone transfers another 100 tokens to the team basket; // 4. ... // Problem is, actually, you can't spend any of these extra 100 // tokens until 96 weeks will elapse since minting finish date. // That's because after next 24 weeks will be unlocked only // 25 tokens more (25% of *minted* tokens) and so on. // So, DO NOT send tokens to the team basket until 96 weeks elapse! function isFrozen( BasketType _basketType, uint _value ) public view returns (bool) { if (!isMintingFinished) { // Allow spend only after minting is finished return true; } if (_basketType == BasketType.foundation) { // Allow to spend foundation tokens only after // 48 weeks after minting is finished return now < mintingStopDate + 48 weeks; } if (_basketType == BasketType.team) { // Team allowed to spend tokens: // 25% - after minting finished date + 24 weeks; // 50% - after minting finished date + 48 weeks; // 75% - after minting finished date + 72 weeks; // 100% - after minting finished date + 96 weeks. if (mintingStopDate + 96 weeks <= now) { return false; } if (now < mintingStopDate + 24 weeks) return true; // Calculate fraction as percents multipled to 10^10. // Without this owner will be able to spend fractions // less than 1% per transaction. uint fractionSpent = spentByTeam.add(_value).mul(1000000000000).div(teamTotal); if (now < mintingStopDate + 48 weeks) { return 250000000000 < fractionSpent; } if (now < mintingStopDate + 72 weeks) { return 500000000000 < fractionSpent; } // from 72 to 96 weeks elapsed return 750000000000 < fractionSpent; } // No restrictions for other token holders return false; } // Save amount of spent tokens by team till 96 weeks after minting // finish date. This is vital because without the check we'll eventually // overflow the uint256. function saveTeamSpent(address _owner, uint _value) internal { if (wpTokensBaskets.isTeam(_owner)) { if (now < mintingStopDate + 96 weeks) spentByTeam = spentByTeam.add(_value); } } /** ---------------------------------------------------------------------- Events */ // Emitted when mint agent (address of a sale contract) // replaced with new one event MintAgentReplaced( address indexed previousMintAgent, address indexed newMintAgent ); // Emitted when new tokens were created and funded to account event Mint(address indexed to, uint256 amount); // Emitted when tokens minting is finished. event MintingFinished(); } contract Killable is Ownable { function kill(address a) external onlyOwner addrNotNull(a) { selfdestruct(a); } } contract Beneficiary is Killable { // Address of account which will receive all ether // gathered from ICO address public beneficiary; // Constructor function Beneficiary() public { beneficiary = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Set new beneficiary for ICO function setBeneficiary(address a) external onlyOwner addrNotNull(a) { beneficiary = a; } } contract TokenSale is Killable, Enums { using SafeMath for uint256; // Type describing: // - the address of the beneficiary of the tokens; // - the final amount of tokens calculated according to the // terms of the WP; // - the amount of Ether (in Wei) if the beneficiary is an investor // This type is used in arrays[8] that should be declare in the heir // contracts. struct tokens { address beneficiary; uint256 extAmount; uint256 ethAmount; } // Sale stage start date/time, Unix timestamp uint32 public start; // Sale stage stop date/time, Unix timestamp uint32 public stop; // Min ether amount for purchase uint256 public minBuyingAmount; // Price of one token, in wei uint256 public currentPrice; // Amount of tokens available, in EXTwei uint256 public remainingSupply; // Amount of earned funds, in wei uint256 public earnedFunds; // Address of Token contract Token public token; // Address of Beneficiary contract - a container // for the beneficiary address Beneficiary internal _beneficiary; // Equals to 10^decimals. // Internally tokens stored as EXTwei (token count * 10^decimals). // Used to convert EXT to EXTwei and vice versa. uint256 internal dec; // Constructor function TokenSale( Token _token, // address of EXT ERC20 token contract Beneficiary beneficiary, // address of container for Ether beneficiary uint256 _supplyAmount // in EXT ) public { token = _token; _beneficiary = beneficiary; // Factor for convertation EXT to EXTwei and vice versa dec = 10 ** uint256(token.decimals()); // convert to EXTwei remainingSupply = _supplyAmount.mul(dec); } // Fallback function. Here we'll receive all investments. function() external payable { purchase(); } // Investments receive logic. Must be overrided in // arbitrary sale agent (per each sale stage). function purchase() public payable; // Return truth if purchase with given _value of ether // (in wei) can be made function canPurchase(uint256 _value) public view returns (bool) { return start <= now && now <= stop && minBuyingAmount <= _value && toEXTwei(_value) <= remainingSupply; } // Return address of crowdfunding beneficiary address. function beneficiary() public view returns (address) { return _beneficiary.beneficiary(); } // Return truth if there are tokens which can be purchased. function isActive() public view returns (bool) { return canPurchase(minBuyingAmount); } // Initialize tokensArray records with actual addresses of WP tokens baskets function setBaskets(tokens[8] memory _tokensArray) internal view { _tokensArray[uint8(BasketType.unknown)].beneficiary = msg.sender; _tokensArray[uint8(BasketType.team)].beneficiary = token.wpTokensBaskets().team(); _tokensArray[uint8(BasketType.foundation)].beneficiary = token.wpTokensBaskets().foundation(); _tokensArray[uint8(BasketType.arr)].beneficiary = token.wpTokensBaskets().arr(); _tokensArray[uint8(BasketType.advisors)].beneficiary = token.wpTokensBaskets().advisors(); _tokensArray[uint8(BasketType.bounty)].beneficiary = token.wpTokensBaskets().bounty(); } // Return amount of tokens (in EXTwei) which can be purchased // at the moment for given amount of ether (in wei). function toEXTwei(uint256 _value) public view returns (uint256) { return _value.mul(dec).div(currentPrice); } // Return amount of bonus tokens (in EXTwei) // Receive amount of tokens (in EXTwei) that will be sale, and bonus percent function bonus(uint256 _tokens, uint8 _bonus) internal pure returns (uint256) { return _tokens.mul(_bonus).div(100); } // Initialize tokensArray records with actual amounts of tokens function calcWPTokens(tokens[8] memory a, uint8 _bonus) internal pure { a[uint8(BasketType.unknown)].extAmount = a[uint8(BasketType.unknown)].extAmount.add( bonus( a[uint8(BasketType.unknown)].extAmount, _bonus ) ); uint256 n = a[uint8(BasketType.unknown)].extAmount; a[uint8(BasketType.team)].extAmount = n.mul(24).div(40); a[uint8(BasketType.foundation)].extAmount = n.mul(20).div(40); a[uint8(BasketType.arr)].extAmount = n.mul(10).div(40); a[uint8(BasketType.advisors)].extAmount = n.mul(4).div(40); a[uint8(BasketType.bounty)].extAmount = n.mul(2).div(40); } // Send received ether (in wei) to beneficiary function transferFunds(uint256 _value) internal { beneficiary().transfer(_value); earnedFunds = earnedFunds.add(_value); } // Method for call mint() in EXT ERC20 contract. // mint() will be called for each record if amount of tokens > 0 function createTokens(tokens[8] memory _tokensArray) internal { for (uint i = 0; i < _tokensArray.length; i++) { if (_tokensArray[i].extAmount > 0) { token.mint( _tokensArray[i].beneficiary, _tokensArray[i].extAmount, _tokensArray[i].ethAmount ); } } } } contract PrivateSale is TokenSale { using SafeMath for uint256; // List of investors allowed to buy tokens at PrivateSale mapping(address => bool) internal allowedInvestors; function PrivateSale(Token _token, Beneficiary _beneficiary) TokenSale(_token, _beneficiary, uint256(400000000)) public { start = 1522627620; stop = 1525046399; minBuyingAmount = 70 szabo; currentPrice = 70 szabo; } function purchase() public payable { require(isInvestorAllowed(msg.sender)); require(canPurchase(msg.value)); transferFunds(msg.value); tokens[8] memory tokensArray; tokensArray[uint8(BasketType.unknown)].extAmount = toEXTwei(msg.value); setBaskets(tokensArray); remainingSupply = remainingSupply.sub( tokensArray[uint8(BasketType.unknown)].extAmount ); calcWPTokens(tokensArray, 30); tokensArray[uint8(BasketType.unknown)].ethAmount = msg.value; createTokens(tokensArray); } // Register new investor function allowInvestor(address a) public onlyOwner addrNotNull(a) { allowedInvestors[a] = true; } // Discard existing investor function denyInvestor(address a) public onlyOwner addrNotNull(a) { delete allowedInvestors[a]; } // Return truth if given account is allowed to buy tokens function isInvestorAllowed(address a) public view returns (bool) { return allowedInvestors[a]; } }
Last resort to return ether. See the last warning at http:solidity.readthedocs.io/en/develop/contracts.htmlfallback-function for such cases.
function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } ERC20 Interface implementation
13,433,362
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol
Redeem tokens of a specific partition. partition Name of the partition. value Number of tokens redeemed. data Information attached to the redemption, by the redeemer./
function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external override nonReentrant { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); }
4,032,085
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Tarot is ERC721Enumerable, ReentrancyGuard, Ownable { uint256 private tarotSpreadPrice = 0.020 ether; uint256 private maxPublicTokenId = 7000; uint256 private maxTokenId = 7777; string[] private tarotCards = [ "The Fool", "The Magician", "The High Pristess", "The Empress", "The Emperor", "The Heirophant", "The Lovers", "The Chariot", "Strength", "The Hermit", "The Wheel of Fortune", "Justice", "The Hanged Man", "Death", "Temperance", "The Devil", "The Tower", "The Star", "The Moon", "The Sun", "Judgement", "The World", "Ace of Wands", "Two of Wands", "Three of Wands", "Four of Wands", "Five of Wands", "Six of Wands", "Seven of Wands", "Eight of Wands", "Nine of Wands", "Ten of Wands", "Page of Wands", "Knight of Wands", "Queen of Wands", "King of Wands", "Ace of Cups", "Two of Cups", "Three of Cups", "Four of Cups", "Five of Cups", "Six of Cups", "Seven of Cups", "Eight of Cups", "Nine of Cups", "Ten of Cups", "Page of Cups", "Knight of Cups", "Queen of Cups", "King of Cups", "Ace of Swords", "Two of Swords", "Three of Swords", "Four of Swords", "Five of Swords", "Six of Swords", "Seven of Swords", "Eight of Swords", "Nine of Swords", "Ten of Swords", "Page of Swords", "Knight of Swords", "Queen of Swords", "King of Swords", "Ace of Pentacles", "Two of Pentacles", "Three of Pentacles", "Four of Pentacles", "Five of Pentacles", "Six of Pentacles", "Seven of Pentacles", "Eight of Pentacles", "Nine of Pentacles", "Ten of Pentacles", "Page of Pentacles", "Knight of Pentacles", "Queen of Pentacles", "King of Pentacles" ]; uint256 public nextTokenId; function random(bytes32 seed) private view returns (uint) { return uint(keccak256(abi.encodePacked(seed, block.difficulty, block.timestamp, msg.sender))); } function drawCard(bytes memory cardPos, uint256 tokenId, bool[78] memory cardDrawn) public view returns (string memory) { uint cardNum; // Draw card until the card drawn isn't drawn before do { cardNum = random(keccak256(abi.encodePacked(cardPos, tokenId))) % tarotCards.length; } while (cardDrawn[cardNum] == true); cardDrawn[cardNum] = true; string memory output = tarotCards[cardNum]; if (random(keccak256(abi.encodePacked("orientation", cardPos, tokenId))) % 2 == 1) { output = string(abi.encodePacked(output, " (r)")); } return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) { bool[78] memory cardDrawn; string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; text-anchor: middle }</style><rect width="100%" height="100%" fill="black" /><polygon points="175,15 300,248 50,248" stroke="#444444" stroke-width="3" /><polygon points="175,310 50,95 300,95 " stroke="#444444" stroke-width="3" /><text x="175" y="21" class="base">'; // 1 parts[1] = drawCard("past", tokenId, cardDrawn); parts[2] = '</text><text x="280" y="252" class="base">'; // 2 parts[3] = drawCard("present", tokenId, cardDrawn); parts[4] = '</text><text x="70" y="252" class="base">'; // 3 parts[5] = drawCard("future", tokenId, cardDrawn); parts[6] = '</text><text x="175" y="319" class="base">'; // 4 parts[7] = drawCard("situation", tokenId, cardDrawn); parts[8] = '</text><text x="70" y="98" class="base">'; // 5 parts[9] = drawCard("obstacle", tokenId, cardDrawn); parts[10] = '</text><text x="280" y="98" class="base">'; // 6 parts[11] = drawCard("opportunity", tokenId, cardDrawn); parts[12] = '</text><text x="175" y="175" class="base">'; // 7 parts[13] = drawCard("advice", tokenId, cardDrawn); parts[14] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Tarot Spread #', toString(tokenId), '", "description": "If there is such thing as destiny, one is destined to make one\'s own destiny.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claimNext() external payable nonReentrant { require(nextTokenId < maxPublicTokenId + 1, "Token ID invalid"); require(msg.value == tarotSpreadPrice); _safeMint(_msgSender(), nextTokenId); nextTokenId++; } function ownerClaim(uint256 tokenId) external nonReentrant onlyOwner { require(tokenId > maxPublicTokenId && tokenId < maxTokenId + 1, "Token ID invalid"); _safeMint(owner(), tokenId); } function remainingPublicTokens() external nonReentrant returns (uint256) { return maxPublicTokenId - nextTokenId + 1; } function withdraw(uint amount) external onlyOwner returns(bool) { require(amount <= address(this).balance); payable(owner()).transfer(amount); return true; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Tarot Protocol", "TAROT") Ownable() { nextTokenId = 1; } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <brecht@loopring.org> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
Draw card until the card drawn isn't drawn before
function drawCard(bytes memory cardPos, uint256 tokenId, bool[78] memory cardDrawn) public view returns (string memory) { uint cardNum; do { cardNum = random(keccak256(abi.encodePacked(cardPos, tokenId))) % tarotCards.length; } while (cardDrawn[cardNum] == true); cardDrawn[cardNum] = true; string memory output = tarotCards[cardNum]; if (random(keccak256(abi.encodePacked("orientation", cardPos, tokenId))) % 2 == 1) { output = string(abi.encodePacked(output, " (r)")); } return output; }
895,869
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibBit.sol
Returns 1 if `b` is true, else 0. Input must be clean.
function rawToUint(bool b) internal pure returns (uint256 z) { assembly { z := b } }
4,875,546
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @title MixDAO Alpha Pass /// @author MilkyTaste @ Ao Collaboration Ltd. /// https://mixdao.club import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./Payable.sol"; contract MixDAOAlphaPass is ERC1155, Payable { uint256 public totalSupply = 0; uint256 public tokenPrice = 0.08 ether; // Token values incremented for gas efficiency uint256 private maxSalePlusOne = 1501; uint256 private maxWalletPlusOne = 4; uint256 private constant MAX_TEAM_CLAIM = 200; mapping(address => uint256) private publicClaimed; // Presale mapping(address => uint256) private presaleClaimed; bytes32 public merkleRoot = ""; // State enum ContractState { OFF, PRESALE, PUBLIC } ContractState public contractState = ContractState.OFF; constructor() ERC1155("ipfs://QmPKxEqPbVcLvSAoCco8DSeUBJh2PquyimUp8bYxRFaZuG") Payable() {} // // Modifiers // /** * Do not allow calls from other contracts. */ modifier noBots() { require(msg.sender == tx.origin, "MixDAOAlphaPass: No bots"); _; } /** * Ensure current state is correct for this method. */ modifier isContractState(ContractState contractState_) { require(contractState == contractState_, "MixDAOAlphaPass: Invalid state"); _; } /** * Ensure amount of tokens to mint is within the transaction limit and total supply limit. */ modifier validTokenAmount(uint256 numTokens) { require((tokenPrice * numTokens) == msg.value, "MixDAOAlphaPass: Ether value sent is not correct"); require((totalSupply + numTokens) < maxSalePlusOne, "MixDAOAlphaPass: Exceeds available tokens"); totalSupply += numTokens; _; } // // Minting // /** * Mint tokens during the public sale. * @param numTokens Number of tokens to mint */ function mintPublic(uint256 numTokens) external payable noBots isContractState(ContractState.PUBLIC) validTokenAmount(numTokens) { require(publicClaimed[msg.sender] + numTokens < maxWalletPlusOne, "MixDAOAlphaPass: Exceeds allowance"); publicClaimed[msg.sender] += numTokens; _mint(msg.sender, 0, numTokens, ""); } /** * Mint tokens during the presale. * @notice This function is only available to those on the allowlist. * @param numTokens The number of tokens to mint. * @param allowance The total number of tokens allowed to mint. * @param proof The Merkle proof used to validate the leaf is in the root. */ function mintPresale( uint256 numTokens, uint256 allowance, bytes32[] calldata proof ) external payable noBots isContractState(ContractState.PRESALE) validTokenAmount(numTokens) { require(presaleClaimed[msg.sender] + numTokens <= allowance, "MixDAOAlphaPass: Exceeds allowance"); bytes32 leaf = keccak256(abi.encode(msg.sender, allowance)); require(verify(merkleRoot, leaf, proof), "MixDAOAlphaPass: Not a valid proof"); presaleClaimed[msg.sender] += numTokens; _mint(msg.sender, 0, numTokens, ""); } /** * Mints remaining team tokens. * @notice This will be called after the FWC claim. * @param numTokens Number of tokens to claim. */ function mintTeam(uint256 numTokens) external onlyOwner { require(numTokens <= MAX_TEAM_CLAIM - totalSupply, "MixDAOAlphaPass: Exceeds allowance"); _mint(msg.sender, 0, numTokens, ""); totalSupply += numTokens; } // // Admin // /** * Set the contract state. * @param contractState_ The new contract state */ function setContractState(ContractState contractState_) external onlyOwner { contractState = contractState_; } /** * Update token price. * @param tokenPrice_ The new token price */ function setTokenPrice(uint256 tokenPrice_) external onlyOwner { tokenPrice = tokenPrice_; } /** * Update maximum number of tokens for sale. * @param maxSale The maximum number of tokens available for sale */ function setMaxSale(uint256 maxSale) external onlyOwner { uint256 maxSalePlusOne_ = maxSale + 1; require(maxSalePlusOne_ < maxSalePlusOne, "MixDAOAlphaPass: Can only reduce supply"); maxSalePlusOne = maxSalePlusOne_; } /** * Update maximum number of tokens per wallet during the public sale. * @notice This parameter only affects the public sale. * @param maxWallet The maximum number of tokens available per wallet for the public sale */ function setMaxWallet(uint256 maxWallet) external onlyOwner { maxWalletPlusOne = maxWallet + 1; } /** * Set the presale Merkle root. * @dev The Merkle root is calculated from [address, allowance] pairs. * @param merkleRoot_ The new merkle roo */ function setMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; } /** * Update the URI. * @param newuri The new URI for the collection */ function setURI(string memory newuri) external onlyOwner { _setURI(newuri); } // // Views // /** * Return sale claim info. * @param addr The address to return sales data for * saleInfo[0]: contractState * saleInfo[1]: maxSale (total available tokens) * saleInfo[2]: totalSupply (minted) * saleInfo[3]: tokenPrice * saleInfo[4]: presaleClaimed (by given address) * saleInfo[5]: maxPerWallet (for public sale) * saleInfo[6]: publicClaimed (by given address) */ function saleInfo(address addr) public view virtual returns (uint256[7] memory) { return [ uint256(contractState), maxSalePlusOne - 1, totalSupply, tokenPrice, presaleClaimed[addr], maxWalletPlusOne - 1, publicClaimed[addr] ]; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view override(ERC1155, ERC2981) returns (bool) { return ERC1155.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId); } /** * Verify the Merkle proof is valid. * @param root The Merkle root. Use the value stored in the contract * @param leaf The leaf. A [address, availableAmt] pair * @param proof The Merkle proof used to validate the leaf is in the root */ function verify( bytes32 root, bytes32 leaf, bytes32[] memory proof ) public pure returns (bool) { return MerkleProof.verify(proof, root, leaf); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @title Payable /// @author MilkyTaste @ Ao Collaboration Ltd. /// Manage payables import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ERC2981.sol"; contract Payable is Ownable, ERC2981, ReentrancyGuard { address public mixDaoAddress = 0x621D420DC767a4fdc3C0eAfE39b915208bc7CC51; constructor() { _setRoyalties(mixDaoAddress, 1000); // 10% royalties } /** * Set the royalties information. * @param recipient recipient of the royalties. * @param value percentage (using 2 decimals - 10000 = 100, 0 = 0). */ function setRoyalties(address recipient, uint256 value) external onlyOwner { require(recipient != address(0), "zero address"); _setRoyalties(recipient, value); } /** * Update MixDAO address for withdraw and royalties. * @param mixDaoAddress_ The new Mix DAO address. */ function setMixDaoAddress(address mixDaoAddress_) external nonReentrant onlyOwner { mixDaoAddress = mixDaoAddress_; _setRoyalties(mixDaoAddress, _royalties.amount); } /** * Withdraw funds. */ function withdraw() external nonReentrant onlyOwner { Address.sendValue(payable(mixDaoAddress), address(this).balance); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 contract ERC2981 is IERC2981 { struct RoyaltyInfo { address recipient; uint24 amount; } RoyaltyInfo internal _royalties; /// @dev Sets token royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties(address recipient, uint256 value) internal { require(value <= 10000, "ERC2981: Too high"); _royalties = RoyaltyInfo(recipient, uint24(value)); } /// @inheritdoc IERC2981 function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981).interfaceId || interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
@inheritdoc IERC2981
function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; }
1,615,681
import "./TokenController.sol"; import "./Whitelist.sol"; import "./NEC.sol"; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract NectarController is TokenController, Whitelist { using SafeMath for uint256; NEC public tokenContract; // The new token for this Campaign address public vaultAddress; // The address to hold the funds donated uint public periodLength = 30; // Contribution windows length in days uint public startTime = 1518523865; // Time of window 1 opening mapping (uint => uint) public windowFinalBlock; // Final block before initialisation of new window /// @dev There are several checks to make sure the parameters are acceptable /// @param _vaultAddress The address that will store the donated funds /// @param _tokenAddress Address of the token contract this contract controls function NectarController( address _vaultAddress, address _tokenAddress ) public { require(_vaultAddress != 0); // To prevent burning ETH tokenContract = NEC(_tokenAddress); // The Deployed Token Contract vaultAddress = _vaultAddress; windowFinalBlock[0] = 5082733; windowFinalBlock[1] = 5260326; } /// @dev The fallback function is called when ether is sent to the contract, it /// simply calls `doTakerPayment()` . No tokens are created when takers contribute. /// `_owner`. Payable is a required solidity modifier for functions to receive /// ether, without this modifier functions will throw if ether is sent to them function () public payable { doTakerPayment(); } function contributeForMakers(address _owner) public payable authorised { doMakerPayment(_owner); } ///////////////// // TokenController interface ///////////////// /// @notice `proxyPayment()` allows the caller to send ether to the Campaign /// but does not create tokens. This functions the same as the fallback function. /// @param _owner Does not do anything, but preserved because of MiniMe standard function. function proxyPayment(address _owner) public payable returns(bool) { doTakerPayment(); return true; } /// @notice `proxyAccountingCreation()` allows owner to create tokens without sending ether via the contract /// Creates tokens, pledging an amount of eth to token holders but not sending it through the contract to the vault /// @param _owner The person who will have the created tokens function proxyAccountingCreation(address _owner, uint _pledgedAmount, uint _tokensToCreate) public onlyOwner returns(bool) { // Ethfinex is a hybrid decentralised exchange // This function is only for use to create tokens on behalf of users of the centralised side of Ethfinex // Because there are several different fee tiers (depending on trading volume) token creation rates may not always be proportional to fees contributed. // For example if a user is trading with a 0.025% fee as opposed to the standard 0.1% the tokensToCreate the pledged fees will be lower than through using the standard contributeForMakers function // Tokens to create must be calculated off-chain using the issuance equation and current parameters of this contract, multiplied depending on user's fee tier doProxyAccounting(_owner, _pledgedAmount, _tokensToCreate); return true; } /// @notice Notifies the controller about a transfer. /// Transfers can only happen to whitelisted addresses /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool) { if (isRegistered(_to) && isRegistered(_from)) { return true; } else { return false; } } /// @notice Notifies the controller about an approval, for this Campaign all /// approvals are allowed by default and no extra notifications are needed /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { if (isRegistered(_owner)) { return true; } else { return false; } } /// @notice Notifies the controller about a burn attempt. Initially all burns are disabled. /// Upgraded Controllers in the future will allow token holders to claim the pledged ETH /// @param _owner The address that calls `burn()` /// @param _tokensToBurn The amount in the `burn()` call /// @return False if the controller does not authorize the approval function onBurn(address _owner, uint _tokensToBurn) public returns(bool) { // This plugin can only be called by the token contract require(msg.sender == address(tokenContract)); uint256 feeTotal = tokenContract.totalPledgedFees(); uint256 totalTokens = tokenContract.totalSupply(); uint256 feeValueOfTokens = (feeTotal.mul(_tokensToBurn)).div(totalTokens); // Destroy the owners tokens prior to sending them the associated fees require (tokenContract.destroyTokens(_owner, _tokensToBurn)); require (address(this).balance >= feeValueOfTokens); require (_owner.send(feeValueOfTokens)); emit LogClaim(_owner, feeValueOfTokens); return true; } ///////////////// // Maker and taker fee payments handling ///////////////// /// @dev `doMakerPayment()` is an internal function that sends the ether that this /// contract receives to the `vault` and creates tokens in the address of the /// `_owner`who the fee contribution was sent by /// @param _owner The address that will hold the newly created tokens function doMakerPayment(address _owner) internal { require ((tokenContract.controller() != 0) && (msg.value != 0) ); tokenContract.pledgeFees(msg.value); require (vaultAddress.send(msg.value)); // Set the block number which will be used to calculate issuance rate during // this window if it has not already been set if(windowFinalBlock[currentWindow()-1] == 0) { windowFinalBlock[currentWindow()-1] = block.number -1; } uint256 newIssuance = getFeeToTokenConversion(msg.value); require (tokenContract.generateTokens(_owner, newIssuance)); emit LogContributions (_owner, msg.value, true); return; } /// @dev `doTakerPayment()` is an internal function that sends the ether that this /// contract receives to the `vault`, creating no tokens function doTakerPayment() internal { require ((tokenContract.controller() != 0) && (msg.value != 0) ); tokenContract.pledgeFees(msg.value); require (vaultAddress.send(msg.value)); emit LogContributions (msg.sender, msg.value, false); return; } /// @dev `doProxyAccounting()` is an internal function that creates tokens /// for fees pledged by the owner function doProxyAccounting(address _owner, uint _pledgedAmount, uint _tokensToCreate) internal { require ((tokenContract.controller() != 0)); if(windowFinalBlock[currentWindow()-1] == 0) { windowFinalBlock[currentWindow()-1] = block.number -1; } tokenContract.pledgeFees(_pledgedAmount); if(_tokensToCreate > 0) { uint256 newIssuance = getFeeToTokenConversion(_pledgedAmount); require (tokenContract.generateTokens(_owner, _tokensToCreate)); } emit LogContributions (msg.sender, _pledgedAmount, true); return; } /// @notice `onlyOwner` changes the location that ether is sent /// @param _newVaultAddress The address that will store the fees collected function setVault(address _newVaultAddress) public onlyOwner { vaultAddress = _newVaultAddress; } /// @notice `onlyOwner` can upgrade the controller contract /// @param _newControllerAddress The address that will have the token control logic function upgradeController(address _newControllerAddress) public onlyOwner { tokenContract.changeController(_newControllerAddress); emit UpgradedController(_newControllerAddress); } ///////////////// // Issuance reward related functions - upgraded by changing controller ///////////////// /// @dev getFeeToTokenConversion (v2) - Controller could be changed in the future to update this function /// @param _contributed - The value of fees contributed during the window function getFeeToTokenConversion(uint256 _contributed) public view returns (uint256) { uint calculationBlock = windowFinalBlock[currentWindow()-1]; uint256 previousSupply = tokenContract.totalSupplyAt(calculationBlock); uint256 initialSupply = tokenContract.totalSupplyAt(windowFinalBlock[0]); // Rate = 1000 * (2-totalSupply/InitialSupply)^2 // This imposes a max possible supply of 2 billion if (previousSupply >= 2 * initialSupply) { return 0; } uint256 newTokens = _contributed.mul(1000).mul(bigInt(2)-(bigInt(previousSupply).div(initialSupply))).mul(bigInt(2)-(bigInt(previousSupply).div(initialSupply))).div(bigInt(1).mul(bigInt(1))); return newTokens; } function bigInt(uint256 input) internal pure returns (uint256) { return input.mul(10 ** 10); } function currentWindow() public constant returns (uint) { return windowAt(block.timestamp); } function windowAt(uint timestamp) public constant returns (uint) { return timestamp < startTime ? 0 : timestamp.sub(startTime).div(periodLength * 1 days) + 1; } /// @dev topUpBalance - This is only used to increase this.balance in the case this controller is used to allow burning function topUpBalance() public payable { // Pledged fees could be sent here and used to payout users who burn their tokens emit LogFeeTopUp(msg.value); } /// @dev evacuateToVault - This is only used to evacuate remaining to ether from this contract to the vault address function evacuateToVault() public onlyOwner{ vaultAddress.transfer(address(this).balance); emit LogFeeEvacuation(address(this).balance); } /// @dev enableBurning - Allows the owner to activate burning on the underlying token contract function enableBurning(bool _burningEnabled) public onlyOwner{ tokenContract.enableBurning(_burningEnabled); } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover function claimTokens(address _token) public onlyOwner { NEC token = NEC(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event LogFeeTopUp(uint _amount); event LogFeeEvacuation(uint _amount); event LogContributions (address _user, uint _amount, bool _maker); event LogClaim (address _user, uint _amount); event UpgradedController (address newAddress); }
Notifies the controller about a burn attempt. Initially all burns are disabled. Upgraded Controllers in the future will allow token holders to claim the pledged ETH _owner The address that calls `burn()` _tokensToBurn The amount in the `burn()` call return False if the controller does not authorize the approval This plugin can only be called by the token contract Destroy the owners tokens prior to sending them the associated fees
function onBurn(address _owner, uint _tokensToBurn) public returns(bool) { require(msg.sender == address(tokenContract)); uint256 feeTotal = tokenContract.totalPledgedFees(); uint256 totalTokens = tokenContract.totalSupply(); uint256 feeValueOfTokens = (feeTotal.mul(_tokensToBurn)).div(totalTokens); require (tokenContract.destroyTokens(_owner, _tokensToBurn)); require (address(this).balance >= feeValueOfTokens); require (_owner.send(feeValueOfTokens)); emit LogClaim(_owner, feeValueOfTokens); return true; }
6,403,991
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } /** * @dev ERC-721 non-fungible token standard. See https://goo.gl/pc9yoS. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` * on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @dev ERC-721 interface for accepting safe transfers. See https://goo.gl/pc9yoS. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } /** * @dev A standard for detecting smart contract interfaces. See https://goo.gl/cxQCse. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } contract BasicValidator { using AddressUtils for address; bytes4 constant ERC165ID = 0x01ffc9a7; bytes4 constant ERC721ID = 0x80ac58cd; bytes4 constant ERC721MetadataID = 0x5b5e139f; bytes4 constant ERC721EnumerableID = 0x780e9d63; constructor( uint256 _caseId, address _target ) { if (_caseId == 1) { sanityCheck(_target); return; } else if (_caseId == 2) { checkERC165Interface(_target); return; } else if (_caseId == 3) { checkERC721Interface(_target); return; } else if (_caseId == 4) { checkERC721MetadataInterface(_target); return; } else if (_caseId == 5) { checkERC721EnumerableInterface(_target); return; } else if (_caseId == 6){ checkBalanceOfZeroAddress(_target); return; } else if (_caseId == 7){ checkMetadataName(_target); return; } else if (_caseId == 8){ checkMetadataSymbol(_target); return; } else if (_caseId == 9){ checkTotalSupply(_target); return; } else if (_caseId == 10){ checkZeroTokenByIndex(_target); return; } assert(false); } /** * @dev Sanity checks * Find the amount of value (ether) assigned to CONTRACT_ADDRESS, it should be greater than or * equal to zero. Find the code_size of CONTRACT_ADDRESS, it should be greater than zero. */ function sanityCheck( address _target ) internal { require(_target.balance >= 0); assert(_target.isContract()); } /** * @dev Check interface 165. */ function checkERC165Interface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC165ID); assert(result); } /** * @dev Check interface ERC721. */ function checkERC721Interface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721ID); assert(result); } /** * @dev Check interface ERC721Metadata. */ function checkERC721MetadataInterface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721MetadataID); assert(result); } /** * @dev Check interface ERC721Enumerable. */ function checkERC721EnumerableInterface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721EnumerableID); assert(result); } /** * @dev balanceOf(0) should throw. */ function checkBalanceOfZeroAddress( address _target ) internal { ERC721(_target).balanceOf(address(0)); } /** * @dev name() should not throw. */ function checkMetadataName( address _target ) internal { ERC721Metadata(_target).name(); } /** * @dev symbol() should not throw. */ function checkMetadataSymbol( address _target ) internal { ERC721Metadata(_target).symbol(); } /** * @dev totalSupply should be greater than 0. */ function checkTotalSupply( address _target ) internal { require(ERC721Enumerable(_target).totalSupply() > 0); } /** * @dev tokenByIndex(0) should not throw. */ function checkZeroTokenByIndex( address _target ) internal { ERC721Enumerable(_target).tokenByIndex(0); } } contract Stub1 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; constructor() {} /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { require(StringUtils.compare2(_data, "") == 0); return MAGIC_ON_ERC721_RECEIVED; } function transferToken( address _contract, uint256 _tokenId, address _receiver ) external { ERC721(_contract).transferFrom(ERC721(_contract).ownerOf(_tokenId), _receiver, _tokenId); } } contract Stub2 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { require(StringUtils.compare2(_data, "ffff") == 0); // bytes memory temp = bytes(_data); //require(temp == bytes(0x0)); return MAGIC_ON_ERC721_RECEIVED; } } contract Stub3 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED_FALSE = 0x150b7a0b; /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { return MAGIC_ON_ERC721_RECEIVED_FALSE; } } contract Stub4 { function test() public pure {} } contract TokenValidator { constructor( uint256 _caseId, address _target, uint256 _tokenId ) { if (_caseId == 1) { checkTokenUri(_target, _tokenId); return; } else if (_caseId == 2) { checkBalanceBasedOnToken(_target, _tokenId); return; } else if (_caseId == 3) { checkNotEmptyOwner(_target, _tokenId); return; } assert(false); } /** * @dev tokenURI(TEST_TOKEN_ID) should not throw. */ function checkTokenUri( address _target, uint256 _tokenId ) internal { ERC721Metadata(_target).tokenURI(_tokenId); } /** * @dev balanceOf(ownerOf(TEST_TOKEN_ID) should be > 0. */ function checkBalanceBasedOnToken( address _target, uint256 _tokenId ) internal { require(ERC721(_target).balanceOf(ERC721(_target).ownerOf(_tokenId)) > 0); } /** * @dev ownerOf(TEST_TOKEN_ID) should return an address > 0. */ function checkNotEmptyOwner( address _target, uint256 _tokenId ) internal { require(ERC721(_target).ownerOf(_tokenId) != address(0)); } } contract TransferValidator { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; address constant stubAddress = 0x85A9916425960aA35B2a527D77C71855DC0215B3; constructor( uint256 _caseId, address _target, uint256 _tokenId, address _giver ) payable { if (_caseId == 1) { checkTransferFromGiver(_target, _tokenId, _giver); return; } else if (_caseId == 2) { getTokenFromGiver(_target, _giver, _tokenId); checkBalanceOnTransfer(_target, _tokenId); return; } else if (_caseId == 3) { getTokenFromGiver(_target, _giver, _tokenId); checkTransferToZeroAddress(_target, _tokenId); return; } else if (_caseId == 4) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferCallBackData(_target, _tokenId); return; } else if (_caseId == 5) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferCallBack(_target, _tokenId); return; } else if (_caseId == 6) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferNoCallBack(_target, _tokenId); return; } else if (_caseId == 7) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferWrongMagicValue(_target, _tokenId); return; } else if (_caseId == 8) { getTokenFromGiver(_target, _giver, _tokenId); checkGetApproved(_target, _tokenId); return; } else if (_caseId == 9) { getTokenFromGiver(_target, _giver, _tokenId); checkApproveAndTransfer(_target, _tokenId); return; } else if (_caseId == 10) { getTokenFromGiver(_target, _giver, _tokenId); checkApprovalForAll(_target, _tokenId); return; } else if (_caseId == 11) { getTokenFromGiver(_target, _giver, _tokenId); checkApproveForAllAndTransfer(_target, _tokenId); return; } else if (_caseId == 12) { getTokenFromGiver(_target, _giver, _tokenId); checkZeroTokenOfOwnerByIndex(_target); return; } else if (_caseId == 13) { getTokenFromGiver(_target, _giver, _tokenId); checkOverflowTokenOfOwnerByIndex(_target); return; } else if (_caseId == 14) { getTokenFromGiver(_target, _giver, _tokenId); return; } assert(false); } function getTokenFromGiver( address _target, address _giver, uint256 _tokenId ) internal { Giver(_giver).getToken{value:1000000 ether}(_target, _tokenId); } /** * @dev transferFrom giver to self, this should throw because giver does not authorize the * transaction. */ function checkTransferFromGiver( address _target, uint256 _tokenId, address _giver ) internal { ERC721(_target).transferFrom(_giver, address(this), _tokenId); } /** * @dev Get a token from giver, transferFrom self to a stub, check balanceOf() stub before and * after transfer, it should be one more. */ function checkBalanceOnTransfer( address _target, uint256 _tokenId ) internal { uint256 balance = ERC721(_target).balanceOf(stubAddress); ERC721(_target).transferFrom(address(this), stubAddress, _tokenId); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get a token from giver, transferFrom to zero address, should throw. */ function checkTransferToZeroAddress( address _target, uint256 _tokenId ) internal { ERC721(_target).transferFrom(address(this), address(0), _tokenId); } /** * @dev Get a token from giver, safe transfer to stub by sending data ffff. Stub throws in * callback if it does not receive ffff. */ function checkSafeTransferCallBackData( address _target, uint256 _tokenId ) internal { Stub2 stub = new Stub2(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId, "ffff"); } /** * @dev Get a token from giver, safe transfer to stub using the default argument. Stub throws in * callback if it does not receive "". */ function checkSafeTransferCallBack( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId); } /** * @dev Get a token from giver, safe transfer to contract stud that does not implement token * receiver, should throw. */ function checkSafeTransferNoCallBack( address _target, uint256 _tokenId ) internal { Stub4 stub = new Stub4(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId, "ffff"); } /** * @dev Get a token from giver, safe transfer to stub, the stub does not return the correct magic * value, the transfer must throw */ function checkSafeTransferWrongMagicValue( address _target, uint256 _tokenId ) internal { Stub3 stub = new Stub3(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId); } /** * @dev Get a token from giver, approve stub, then check getApproved stub; */ function checkGetApproved( address _target, uint256 _tokenId ) internal { ERC721(_target).approve(stubAddress, _tokenId); require(ERC721(_target).getApproved(_tokenId) == stubAddress); } /** * @dev Get a token from giver, approve stub, then have stub transferFrom to stub2. */ function checkApproveAndTransfer( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).approve(address(stub), _tokenId); uint256 balance = ERC721(_target).balanceOf(stubAddress); stub.transferToken(_target, _tokenId, stubAddress); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get a token from giver, approveForAll to stub, then check isApprovedForAll. */ function checkApprovalForAll( address _target, uint256 _tokenId ) internal { ERC721(_target).setApprovalForAll(stubAddress, true); require(ERC721(_target).isApprovedForAll(address(this), stubAddress)); } /** * @dev Get a token from giver, approveFor All to stub, then have stub transferFrom to stub2. */ function checkApproveForAllAndTransfer( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).setApprovalForAll(address(stub), true); uint256 balance = ERC721(_target).balanceOf(stubAddress); stub.transferToken(_target, _tokenId, stubAddress); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get token from giver, find balanceOf(self), tokenOfOwnerByIndex(0) should not throw. */ function checkZeroTokenOfOwnerByIndex( address _target ) internal { require(ERC721(_target).balanceOf(address(this)) > 0); ERC721Enumerable(_target).tokenOfOwnerByIndex(address(this), 0); } /** * @dev Get token from giver, find balanceOf(self), tokenOfOwnerByIndex(balanceOf(self)) should * throw. */ function checkOverflowTokenOfOwnerByIndex( address _target ) internal { uint256 balance = ERC721(_target).balanceOf(address(this)); ERC721Enumerable(_target).tokenOfOwnerByIndex(address(this), balance); } } library StringUtils { /// @dev Does a byte-by-byte lexicographical comparison of two strings. /// @return a negative number if `_a` is smaller, zero if they are equal /// and a positive numbe if `_b` is smaller. function compare(string memory _a, string memory _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function compare2(bytes memory _a, string memory _b) internal returns (int) { bytes memory a = _a; bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// @dev Compares two strings and returns true iff they are equal. function equal(string memory _a, string memory _b) internal returns (bool) { return compare(_a, _b) == 0; } /// @dev Finds the index of the first occurrence of _needle in _haystack function indexOf(string memory _haystack, string memory _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) // found the first char of b { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) // search until the chars don't match or until we reach the end of a or b { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } } contract Giver { /** * @dev Do not send 1 mil ether to this function it is strictly for testing purposes. */ function getToken( address _contract, uint256 _tokenId ) external payable { require(msg.value >= 1000000 ether); ERC721(_contract).transferFrom(ERC721(_contract).ownerOf(_tokenId), msg.sender, _tokenId); } }
@todo unroll the loop into increments of 32 and do full 32 byte comparisons
function compare2(bytes memory _a, string memory _b) internal returns (int) { bytes memory a = _a; bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; }
993,549
./partial_match/7700/0x9B2920e72dF6E1A7053bEa7235c65079F5104398/sources/contracts/Router.sol
performs chained getAmountOut calculations on any number of pairs
function getAmountOut( uint256 amountIn, address tokenIn, address tokenOut ) external view returns (uint256 amount, bool stable) { address pair = pairFor(tokenIn, tokenOut, true); uint256 amountStable; uint256 amountVolatile; if (IPairFactory(factory).isPair(pair)) { amountStable = IPair(pair).getAmountOut(amountIn, tokenIn); } pair = pairFor(tokenIn, tokenOut, false); if (IPairFactory(factory).isPair(pair)) { amountVolatile = IPair(pair).getAmountOut(amountIn, tokenIn); } return amountStable > amountVolatile ? (amountStable, true) : (amountVolatile, false); }
3,505,585
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ // Sources flattened with hardhat v2.9.2 https://hardhat.org // File contracts/dependencies/Context.sol /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File contracts/dependencies/EnumerableSet.sol /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File contracts/dependencies/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/dependencies/AccessControl.sol /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/dependencies/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); /* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } */ } // File contracts/dependencies/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/dependencies/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File contracts/dependencies/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File contracts/dependencies/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File contracts/dependencies/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File contracts/dependencies/ERC721A.sol error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; mapping (address => bool) public whitelists; mapping (uint => string) public colors; uint public round = 1; // to block trading of redeemed NFT in current round mapping (uint => uint) public tag; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function _getbaseURI() internal view returns (string memory) { return _baseURI; } // 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) internal _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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); _paused = false; } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _getbaseURI(); // return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; return string(abi.encodePacked(baseURI, tokenId.toString(), ".json")); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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 _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity, string[] memory _colors) internal { _safeMint(to, quantity, '', _colors); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data, string[] memory _colors ) internal { _mint(to, quantity, _data, _colors, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, string[] memory _colors, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); colors[updatedIndex] = _colors[updatedIndex - startTokenId]; if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { colors[updatedIndex] = _colors[updatedIndex - startTokenId]; emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _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); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = 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; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @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); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * 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`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual { require(!paused(), "ERC721Pausable: token transfer while paused"); require(tag[startTokenId] != round, "token already redeemed"); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { require(!paused(), "ERC721Pausable: token transfer while paused"); require(tag[tokenId] != round, "token already redeemed"); } /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * 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` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/NonFungibleToken.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract NonFungibleToken is Context, AccessControl, ERC721A { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); address public owner; bool public whitelistingEnabled = false; bool public mintingEnabled = true; uint256 public maxPerWallet = 100; bool public freezeMetadata = false; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseURI) public ERC721A(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); owner = msg.sender; } function setFreezeMetadata() public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); require(! freezeMetadata, "NonFungibleToken: already frozen !"); freezeMetadata = true; } function setURI(string memory baseURI) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); require(! freezeMetadata, "Metadata frozen !"); _setBaseURI(baseURI); } function setMaxPerWallet(uint256 _maxPerWallet) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); maxPerWallet = _maxPerWallet; } function setOwner(address _owner) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role to mint"); owner = _owner; } function toggleMinting(bool _bool) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role to mint"); mintingEnabled = _bool; } function toggleWhitelisting(bool _toggle) public virtual { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); whitelistingEnabled = _toggle; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public whenNotPaused { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public whenPaused { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); _unpause(); } function Whitelist(address[] memory _beneficiaries) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelists[_beneficiaries[i]] = true; } } function bulkMint(address[] memory _beneficiaries, string[] memory _colors) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); for (uint256 i = 0; i < _beneficiaries.length; i++) { string[] memory color = new string[](1); color[0] = _colors[i]; _safeMint(_beneficiaries[i], 1, color); } } function setRound(uint _round) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); round = _round; } function tagNft(uint nftId) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); tag[nftId] = round; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_getbaseURI(), "contract-metadata.json")); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 quantity, string[] memory _colors) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "NonFungibleToken: must have minter role to mint"); require(whitelists[to] || ! whitelistingEnabled, "User not whitelisted !"); require(mintingEnabled, "Minting not enabled !"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _safeMint(to, quantity, _colors); require(balanceOf(to) <= maxPerWallet, "Max NFTs reached by wallet"); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721A) { //super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } }
Returns to normal state. Requirements: - The contract must be paused./
function unpause() public whenPaused { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleToken: must have admin role"); _unpause(); }
15,159,908
./full_match/11155111/0x40b26bAD8E72c89833fA45653A1f5277fAfCa251/sources/contracts/Artwork.sol
Get All Auction Artworks
function getAuctionArtworks() public view returns (AuctionArt[] memory) { AuctionArt[] memory allAuctionArtworks = new AuctionArt[]( auction_art_count ); for (uint i = 0; i < auction_art_count; i++) { AuctionArt storage item = auction_arts[i]; allAuctionArtworks[i] = item; } return allAuctionArtworks; }
3,788,589
pragma solidity ^0.4.24; import "./owned.sol"; import "./balance.sol"; contract Betting is Owned, Balance { mapping(uint => Game) games; enum GameStatus { FinishedDraw, FinishedOne, FinishedTwo, Open } enum OrderType { Buy, Sell } enum OrderStatus { Open, Matched, Win, Lose, Closed } enum OrderOutcome {Draw, One, Two } uint public totalGames; uint80 constant NONE = uint80(0); // We use the struct datatype to store the event information. struct Game { uint id; string homeTeam; string awayTeam; string category; uint startDate; uint endDate; GameStatus status; address owner; uint totalOrders; mapping (uint => Order) orders; } struct OrderMatched { uint matchedOrderId; uint amount; // 100 } struct Order { uint id; address player; uint gameId; OrderType orderType; // buy or sell uint amount; // 100 uint odd; // 1.5 OrderOutcome outcome; // 1, x, 2 OrderStatus status; uint matchedAmount; // 100 uint totalMatched; mapping(uint => OrderMatched) matchedOrders; } /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) Balance(initialSupply, tokenName, tokenSymbol) public { totalGames = 0; } /** * Add Game Event */ event GameEvent(uint gameId, string homeTeam, string awayTeam, string category, uint startDate, uint endDate, uint status, address owner, uint totalOrders); /** * Place order event */ event OrderEvent(uint orderId, address player, uint gameId, OrderType orderType, uint amount, uint odd, uint outcome, uint status, uint matchedAmount, uint totalMatched); /** * Add Game */ function addGame(string _homeTeam, string _awayTeam, string _category, uint _startDate, uint _endDate, uint status, address owner) public returns (uint) { // require (now > _startDate); require(_startDate < _endDate); totalGames += 1; uint gameIndex = totalGames - 1; Game memory game = Game(gameIndex, _homeTeam, _awayTeam, _category, _startDate, _endDate, GameStatus(status), owner, 0); games[gameIndex] = game; emitGameEvent(game); return gameIndex; } /** * Finish game by gameId and result */ function finishGame(uint _gameId, uint outcome) public { Game storage game = games[_gameId]; require(game.status == GameStatus.Open); for (uint i = 0; i < game.totalOrders; i++) { Order storage order = game.orders[i]; if (order.status != OrderStatus.Closed) { if (order.status == OrderStatus.Matched) { unblockTokensByOrder(order); // unblockTokensByOrder(game.orders[order.matchedOrderId]); if (order.orderType == OrderType.Buy){ //if is Buy order if (order.outcome == OrderOutcome(outcome)) { //if game's outcome equals order outcome order.status = OrderStatus.Win; // game.orders[order.matchedOrderId].status = OrderStatus.Lose; }else{ //if game's outcome does not equals order outcome order.status = OrderStatus.Lose; // game.orders[order.matchedOrderId].status = OrderStatus.Win; } } else { // if is Sell order if (order.outcome == OrderOutcome(outcome)) { //if game's outcome equals order outcome order.status = OrderStatus.Lose; // game.orders[order.matchedOrderId].status = OrderStatus.Win; }else{ //if game's outcome does not equals order outcome order.status = OrderStatus.Win; // game.orders[order.matchedOrderId].status = OrderStatus.Lose; } } if (order.orderType == OrderType.Buy){ for (uint j = 0; j < order.totalMatched; j++) { uint matchedAmount = order.matchedOrders[j].amount; uint matchedOrderId = order.matchedOrders[j].matchedOrderId; Order memory matchedOrder = game.orders[matchedOrderId]; transferTokensByOrder(order, matchedOrder, matchedAmount, outcome); } } //send order events for update emitOrderEvent(order); // emitOrderEvent(game.orders[order.matchedOrderId]); } if(order.status == OrderStatus.Open) { //unblock tokens unblockTokensByOrder(order); //update order status which is not matched as closed order.status = OrderStatus.Closed; //send event on this order for update emitOrderEvent(order); } } } game.status = GameStatus(outcome); emitGameEvent(game); } /** * Get Game by id */ function getGame(uint _gameId) public view returns (uint, string, string, string, uint, uint, GameStatus, address, uint) { Game memory game = games[_gameId]; return (game.id, game.homeTeam, game.awayTeam, game.category, game.startDate, game.endDate, game.status, game.owner, game.totalOrders); } /** * Get order by game id and order id */ function getOrderById(uint _gameId, uint _orderId) public view returns (uint, address, uint, OrderType, uint, uint, OrderOutcome, OrderStatus, uint) { Order memory order = games[_gameId].orders[_orderId]; return (order.id, order.player, order.gameId, order.orderType, order.amount, order.odd, order.outcome, order.status, order.matchedAmount); } /** * Place order on the game */ function placeOrder(uint _gameId, uint _orderType, uint _amount, uint _odd, uint _outcome, address _player) public payable returns (uint) { require (_amount > 0); require (_odd > 0); Game storage game = games[_gameId]; require (game.status == GameStatus.Open); // require (now < game.startDate); uint newId = game.totalOrders; Order memory newOrder = Order(newId, _player, _gameId, OrderType(_orderType), _amount, _odd, OrderOutcome(_outcome), OrderStatus.Open, 0, 0); blockTokensByOrderType(newOrder); //save order game.orders[newId] = newOrder; //increase orders number game.totalOrders += 1; //check matched checkMatched(_gameId, newId); return newOrder.id; } /** * Give free tokens to signed users */ function giveFreeTokens(uint _amount, address _toUser) public returns (bool) { if(balanceOf[_toUser].owner != _toUser){ Wallet memory wallet = Wallet(0, 0, _toUser); balanceOf[_toUser] = wallet; } transferTokens(msg.sender, _toUser, _amount); return true; } /** * Get balance */ function getBalance() public view returns (uint, uint, address) { Wallet memory wallet = balanceOf[msg.sender]; return (wallet.amount, wallet.blockAmount, wallet.owner); } /** * Block tokens by order type */ function blockTokensByOrderType(Order order) private { if(order.orderType == OrderType.Buy){ //Block tokens for this orders when is Buy order blockTokens(order.player, order.amount); }else{ //Block tokens for this orders when is Sell order uint amount = order.amount * order.odd / 100; blockTokens(order.player, amount); } } /** * Unblock tokens by order type * * amount = 300 * odd = 140 * 300 00 140 * 4200000 */ function unblockTokensByOrder(Order order) private { if(order.orderType == OrderType.Buy){ //Block tokens for this orders unblockTokens(order.player, order.amount); }else{ //Block tokens for this orders uint amount = order.amount * order.odd / 100; unblockTokens(order.player, amount); } } event LogUint(string label, uint value); function log(string label, uint value) private { emit LogUint(label, value); } /** * Transfer tokens by order type */ function transferTokensByOrder(Order order, Order matchedOrder, uint matchedAmount, uint outcome) private { uint transferAmount; address from; address to; // log('test-gigaaaa', matchedAmount); // log('order.amount', order.amount); if(order.orderType == OrderType.Buy){ // if is buy order transferAmount = matchedAmount * order.odd / 100 - matchedAmount; if (order.outcome == OrderOutcome(outcome)) { //if game's outcome equals order outcome from = matchedOrder.player; to = order.player; }else{ //if game's outcome does not equals order outcome from = order.player; to = matchedOrder.player; } }else{ // if is Sell order transferAmount = matchedAmount; if (order.outcome == OrderOutcome(outcome)) { //if game's outcome equals order outcome from = order.player; to = matchedOrder.player; }else{ //if game's outcome does not equals order outcome from = matchedOrder.player; to = order.player; } } // log('matchedAmount', matchedAmount); // log('transferAmount', transferAmount); //transfer money transferTokens(from, to, transferAmount); } /** * Check orders if matched change status as matched and block tokens */ function checkMatched(uint _gameId, uint _newOrderId) private returns(Order){ Game storage game = games[_gameId]; Order storage newOrder = game.orders[_newOrderId]; for (uint i = 0; i < game.totalOrders; i++) { Order storage order = game.orders[i]; uint avalaibleAmount = order.amount - order.matchedAmount; uint requestAmount = newOrder.amount - newOrder.matchedAmount; if(requestAmount <=0){ break; } if ( order.orderType != newOrder.orderType && order.odd == newOrder.odd && order.outcome == newOrder.outcome && order.player != newOrder.player && avalaibleAmount > 0 && requestAmount > 0 ) { uint matchedAmount = avalaibleAmount; if(avalaibleAmount > requestAmount){ matchedAmount = requestAmount; } order.status = OrderStatus.Matched; order.matchedAmount = order.matchedAmount + matchedAmount; order.matchedOrders[order.totalMatched] = OrderMatched(newOrder.id, matchedAmount); order.totalMatched = order.totalMatched + 1; newOrder.status = OrderStatus.Matched; newOrder.matchedOrders[newOrder.totalMatched] = OrderMatched(order.id, matchedAmount); newOrder.matchedAmount = newOrder.matchedAmount + matchedAmount; newOrder.totalMatched = newOrder.totalMatched + 1; emitOrderEvent(order); } } emitOrderEvent(newOrder); return newOrder; } function emitOrderEvent(Order order) private { emit OrderEvent (order.id, order.player, order.gameId, order.orderType, order.amount, order.odd, uint(order.outcome), uint(order.status), order.matchedAmount, order.totalMatched); } function emitGameEvent(Game game) private { emit GameEvent(game.id, game.homeTeam, game.awayTeam, game.category, game.startDate, game.endDate, uint(game.status), game.owner, game.totalOrders); } }
Give free tokens to signed users/
function giveFreeTokens(uint _amount, address _toUser) public returns (bool) { function getGame(uint _gameId) public view } function getOrderById(uint _gameId, uint _orderId) public view } function placeOrder(uint _gameId, uint _orderType, uint _amount, uint _odd, uint _outcome, address _player) } if(balanceOf[_toUser].owner != _toUser){ Wallet memory wallet = Wallet(0, 0, _toUser); balanceOf[_toUser] = wallet; } transferTokens(msg.sender, _toUser, _amount); return true; }
15,811,237
./full_match/5/0xBeFb659aE97c5E4fc1494b1e994bC2B219D5F581/sources/contracts/libraries/LibQuorumGovernance.sol
Calculate the weighted pass rate The weight is based upon the ownership units of each member e.g. if Alice and Bob are the group members, they have 60 and 40 units respectively. So the group total is 100 units. so their weights are 60% (60/100100) for Alice and 40% (40/100100) for Bob. members the members to check the pass rate of return the pass rate percentage of `members` (e.g. 46%)
function _calculatePassRate(address[] memory members) internal view returns (uint256) { uint256 totalSignersUnits; for (uint256 i = 0; i < members.length; i++) { totalSignersUnits += LibOwnership._ownershipUnits(members[i]); } uint256 totalUnits = LibOwnership._totalOwnershipUnits(); require(totalUnits > 0, "Governance: units can't be 0"); return (totalSignersUnits * LibPercentage.PERCENTAGE_DIVIDER) / totalUnits; }
7,033,369
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../structs/Payment.sol"; library LessorsLib { struct Lessors { mapping (address => Lessor) _lessors; } struct Lessor { address payable owner; uint256 numOfProperties; Property[] properties; } struct Property { uint id; string title; string description; string imgUrl; uint256 montlyPrice; uint256 depositAmount; uint256 depositPrice; address lessor; address payable tenant; Payment lastPayment; uint nextPayment; bool available; } /** * @dev create new property to this lessor */ function createProperty( Lessors storage lessors, string memory _title, string memory _description, string memory _imgUrl, uint256 _amount, uint256 _deposit ) internal returns(Lessor storage lessor) { Property memory property; lessor = lessors._lessors[msg.sender]; property.title = _title; property.description = _description; property.imgUrl = _imgUrl; property.montlyPrice = _amount; property.depositPrice = _deposit; property.available = true; property.lessor = msg.sender; property.id = lessor.numOfProperties++; lessor.properties.push(property); } /** * @dev retrieve a lessor property */ function getLessors(Lessors storage lessors, address[] memory numOfLessors) view internal returns(Lessor[] memory) { uint256 numLength = numOfLessors.length; Lessor[] memory memoryArray = new Lessor[]( numOfLessors.length); for (uint256 i = 0; i < numLength; i++) { memoryArray[i] = lessors._lessors[numOfLessors[i]]; } return memoryArray; } /** * @dev retrieve a lessor property */ function getLessor(Lessors storage lessors, address _lessorAddress) view internal returns(Lessor storage) { return lessors._lessors[_lessorAddress]; } /** * @dev retrieve a lessor property */ function getLessorProperty(Lessors storage lessors, address _lessorAddress, uint _propertyId) view internal returns(Property memory) { return lessors._lessors[_lessorAddress].properties[_propertyId]; } }
retrieve a lessor property/
function getLessor(Lessors storage lessors, address _lessorAddress) view internal returns(Lessor storage) { return lessors._lessors[_lessorAddress]; }
12,887,125
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/Verifiers.sol
Internal view function to validate that a given order is fillable and not cancelled based on the order status. orderHash The order hash. orderStatus The status of the order, including whether it has been cancelled and the fraction filled. onlyAllowUnused A boolean flag indicating whether partial fills are supported by the calling function. revertOnInvalid A boolean indicating whether to revert if the order has been cancelled or filled beyond the allowable amount. return valid A boolean indicating whether the order is valid./ Ensure that the order has not been cancelled. Only revert if revertOnInvalid has been supplied as true. If the order is not entirely unused... ensure the order has not been partially filled when not allowed. Always revert on partial fills when onlyAllowUnused is true. Otherwise, ensure that order has not been entirely filled. Only revert if revertOnInvalid has been supplied as true.
function _verifyOrderStatus( bytes32 orderHash, OrderStatus storage orderStatus, bool onlyAllowUnused, bool revertOnInvalid ) internal view returns (bool valid) { if (orderStatus.isCancelled) { if (revertOnInvalid) { _revertOrderIsCancelled(orderHash); } } if (orderStatusNumerator != 0) { if (onlyAllowUnused) { _revertOrderPartiallyFilled(orderHash); } else if (orderStatusNumerator >= orderStatus.denominator) { if (revertOnInvalid) { _revertOrderAlreadyFilled(orderHash); } } } }
4,301,140
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./token/IAgoraToken.sol"; import "./AgoraSpace_utils/RankManager.sol"; /// @title A contract for staking tokens contract AgoraSpace is RankManager { // Tokens managed by the contract address public immutable token; address public immutable stakeToken; // For timelock mapping(address => LockedItem[]) internal timelocks; struct LockedItem { uint256 expires; uint256 amount; uint256 rankId; } // For storing balances struct Balance { uint256 locked; uint256 unlocked; } mapping(uint256 => mapping(address => Balance)) public rankBalances; event Deposit(address indexed wallet, uint256 amount); event Withdraw(address indexed wallet, uint256 amount); event EmergencyWithdraw(address indexed wallet, uint256 amount); error InsufficientBalance(uint256 rankId, uint256 available, uint256 required); error TooManyDeposits(); error NonPositiveAmount(); /// @param _tokenAddress The address of the token to be staked, that the contract accepts /// @param _stakeTokenAddress The address of the token that's given in return constructor(address _tokenAddress, address _stakeTokenAddress) { token = _tokenAddress; stakeToken = _stakeTokenAddress; } /// @notice Accepts tokens, locks them and gives different tokens in return /// @dev The depositor should approve the contract to manage stakingTokens /// @dev For minting stakeTokens, this contract should be the owner of them /// @param _amount The amount to be deposited in the smallest unit of the token /// @param _rankId The id of the rank to be deposited to /// @param _consolidate Calls the consolidate function if true function deposit( uint256 _amount, uint256 _rankId, bool _consolidate ) external notFrozen { if (_amount < 1) revert NonPositiveAmount(); if (timelocks[msg.sender].length >= 64) revert TooManyDeposits(); if (numOfRanks < 1) revert NoRanks(); if (_rankId >= numOfRanks) revert InvalidRank(); if ( rankBalances[_rankId][msg.sender].unlocked + rankBalances[_rankId][msg.sender].locked + _amount >= ranks[_rankId].goalAmount ) { unlockBelow(_rankId, msg.sender); } else if (_consolidate && _rankId > 0) { consolidate(_amount, _rankId, msg.sender); } LockedItem memory timelockData; timelockData.expires = block.timestamp + ranks[_rankId].minDuration * 1 minutes; timelockData.amount = _amount; timelockData.rankId = _rankId; timelocks[msg.sender].push(timelockData); rankBalances[_rankId][msg.sender].locked += _amount; IAgoraToken(stakeToken).mint(msg.sender, _amount); IERC20(token).transferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); } /// @notice If the timelock is expired, gives back the staked tokens in return for the tokens obtained while depositing /// @dev This contract should have sufficient allowance to be able to burn stakeTokens from the user /// @dev For burning stakeTokens, this contract should be the owner of them /// @param _amount The amount to be withdrawn in the smallest unit of the token /// @param _rankId The id of the rank to be withdrawn from function withdraw(uint256 _amount, uint256 _rankId) external notFrozen { if (_amount < 1) revert NonPositiveAmount(); uint256 expired = viewExpired(msg.sender, _rankId); if (rankBalances[_rankId][msg.sender].unlocked + expired < _amount) revert InsufficientBalance({ rankId: _rankId, available: rankBalances[_rankId][msg.sender].unlocked + expired, required: _amount }); unlockExpired(msg.sender); rankBalances[_rankId][msg.sender].unlocked -= _amount; IAgoraToken(stakeToken).burn(msg.sender, _amount); IERC20(token).transfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /// @notice Checks the locked tokens for an account and unlocks them if they're expired /// @param _investor The address whose tokens should be checked function unlockExpired(address _investor) public { uint256[] memory expired = new uint256[](numOfRanks); LockedItem[] storage usersLocked = timelocks[_investor]; int256 usersLockedLength = int256(usersLocked.length); for (int256 i = 0; i < usersLockedLength; i++) { if (usersLocked[uint256(i)].expires <= block.timestamp) { // Collect expired amounts per ranks expired[usersLocked[uint256(i)].rankId] += usersLocked[uint256(i)].amount; // Remove expired locks usersLocked[uint256(i)] = usersLocked[uint256(usersLockedLength) - 1]; usersLocked.pop(); usersLockedLength--; i--; } } // Move expired amounts from locked to unlocked for (uint256 i = 0; i < numOfRanks; i++) { if (expired[i] > 0) { rankBalances[i][_investor].locked -= expired[i]; rankBalances[i][_investor].unlocked += expired[i]; } } } /// @notice Unlocks every deposit below a certain rank /// @dev Should be called, when the minimum of a rank is reached /// @param _investor The address whose tokens should be checked /// @param _rankId The id of the rank to be checked function unlockBelow(uint256 _rankId, address _investor) internal { LockedItem[] storage usersLocked = timelocks[_investor]; int256 usersLockedLength = int256(usersLocked.length); uint256[] memory unlocked = new uint256[](numOfRanks); for (int256 i = 0; i < usersLockedLength; i++) { if (usersLocked[uint256(i)].rankId < _rankId) { // Collect the amount to be unlocked per rank unlocked[usersLocked[uint256(i)].rankId] += usersLocked[uint256(i)].amount; // Remove expired locks usersLocked[uint256(i)] = usersLocked[uint256(usersLockedLength) - 1]; usersLocked.pop(); usersLockedLength--; i--; } } // Move unlocked amounts from locked to unlocked for (uint256 i = 0; i < numOfRanks; i++) { if (unlocked[i] > 0) { rankBalances[i][_investor].locked -= unlocked[i]; rankBalances[i][_investor].unlocked += unlocked[i]; } } } /// @notice Collects the investments up to a certain rank if it's needed to reach the minimum /// @dev There must be more than 1 rank /// @dev The minimum should not be reached with the new deposit /// @dev The deposited amount must be locked after the function call /// @param _amount The amount to be deposited /// @param _rankId The id of the rank to be deposited to /// @param _investor The address which made the deposit function consolidate( uint256 _amount, uint256 _rankId, address _investor ) internal { uint256 consolidateAmount = ranks[_rankId].goalAmount - rankBalances[_rankId][_investor].unlocked - rankBalances[_rankId][_investor].locked - _amount; uint256 totalBalanceBelow; uint256 lockedBalance; uint256 unlockedBalance; LockedItem[] storage usersLocked = timelocks[_investor]; int256 usersLockedLength = int256(usersLocked.length); for (uint256 i = 0; i < _rankId; i++) { lockedBalance = rankBalances[i][_investor].locked; unlockedBalance = rankBalances[i][_investor].unlocked; if (lockedBalance > 0) { totalBalanceBelow += lockedBalance; rankBalances[i][_investor].locked = 0; } if (unlockedBalance > 0) { totalBalanceBelow += unlockedBalance; rankBalances[i][_investor].unlocked = 0; } } if (totalBalanceBelow > 0) { LockedItem memory timelockData; // Iterate over the locked list and unlock everything below the rank for (int256 i = 0; i < usersLockedLength; i++) { if (usersLocked[uint256(i)].rankId < _rankId) { usersLocked[uint256(i)] = usersLocked[uint256(usersLockedLength) - 1]; usersLocked.pop(); usersLockedLength--; i--; } } // Create a new locked item and lock it for the rank's duration timelockData.expires = block.timestamp + ranks[_rankId].minDuration * 1 minutes; timelockData.rankId = _rankId; if (totalBalanceBelow > consolidateAmount) { // Set consolidateAmount as the locked amount timelockData.amount = consolidateAmount; rankBalances[_rankId][_investor].locked += consolidateAmount; rankBalances[_rankId][_investor].unlocked += totalBalanceBelow - consolidateAmount; } else { // Set totalBalanceBelow as the locked amount timelockData.amount = totalBalanceBelow; rankBalances[_rankId][_investor].locked += totalBalanceBelow; } timelocks[_investor].push(timelockData); } } /// @notice Gives back all the staked tokens in exchange for the tokens obtained, regardless of timelock /// @dev Can only be called when the contract is frozen function emergencyWithdraw() external { if (!frozen) revert SpaceIsNotFrozen(); uint256 totalBalance; uint256 lockedBalance; uint256 unlockedBalance; for (uint256 i = 0; i < numOfRanks; i++) { lockedBalance = rankBalances[i][msg.sender].locked; unlockedBalance = rankBalances[i][msg.sender].unlocked; if (lockedBalance > 0) { totalBalance += lockedBalance; rankBalances[i][msg.sender].locked = 0; } if (unlockedBalance > 0) { totalBalance += unlockedBalance; rankBalances[i][msg.sender].unlocked = 0; } } if (totalBalance < 1) revert NonPositiveAmount(); delete timelocks[msg.sender]; IAgoraToken(stakeToken).burn(msg.sender, totalBalance); IERC20(token).transfer(msg.sender, totalBalance); emit EmergencyWithdraw(msg.sender, totalBalance); } /// @notice Returns all the timelocks a user has in an array /// @param _wallet The address of the user /// @return An array containing structs with fields "expires", "amount" and "rankId" function getTimelocks(address _wallet) external view returns (LockedItem[] memory) { return timelocks[_wallet]; } /// @notice Sums the locked tokens for an account by ranks if they were expired /// @param _investor The address whose tokens should be checked /// @param _rankId The id of the rank to be checked /// @return The total amount of expired, but not unlocked tokens in the rank function viewExpired(address _investor, uint256 _rankId) public view returns (uint256) { uint256 expiredAmount; LockedItem[] memory usersLocked = timelocks[_investor]; uint256 usersLockedLength = usersLocked.length; for (uint256 i = 0; i < usersLockedLength; i++) { if (usersLocked[i].rankId == _rankId && usersLocked[i].expires <= block.timestamp) { expiredAmount += usersLocked[i].amount; } } return expiredAmount; } }
Sums the locked tokens for an account by ranks if they were expired _investor The address whose tokens should be checked _rankId The id of the rank to be checked return The total amount of expired, but not unlocked tokens in the rank
function viewExpired(address _investor, uint256 _rankId) public view returns (uint256) { uint256 expiredAmount; LockedItem[] memory usersLocked = timelocks[_investor]; uint256 usersLockedLength = usersLocked.length; for (uint256 i = 0; i < usersLockedLength; i++) { if (usersLocked[i].rankId == _rankId && usersLocked[i].expires <= block.timestamp) { expiredAmount += usersLocked[i].amount; } } return expiredAmount; }
915,140
pragma solidity ^0.4.24; /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd interface ERC721 /* is ERC165 */ { // /// @dev This emits when ownership of any NFT changes by any mechanism. // /// This event emits when NFTs are created (`from` == 0) and destroyed // /// (`to` == 0). Exception: during contract creation, any number of NFTs // /// may be created and assigned without emitting Transfer. At the time of // /// any transfer, the approved address for that NFT (if any) is reset to none. // event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); // /// @dev This emits when the approved address for an NFT is changed or // /// reaffirmed. The zero address indicates there is no approved address. // /// When a Transfer event emits, this also indicates that the approved // /// address for that NFT (if any) is reset to none. // event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); // /// @dev This emits when an operator is enabled or disabled for an owner. // /// The operator can manage all NFTs of the owner. // event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); // /// @notice Transfers the ownership of an NFT from one address to another address // /// @dev Throws unless `msg.sender` is the current owner, an authorized // /// operator, or the approved address for this NFT. Throws if `_from` is // /// not the current owner. Throws if `_to` is the zero address. Throws if // /// `_tokenId` is not a valid NFT. When transfer is complete, this function // /// checks if `_to` is a smart contract (code size > 0). If so, it calls // /// `onERC721Received` on `_to` and throws if the return value is not // /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. // /// @param _from The current owner of the NFT // /// @param _to The new owner // /// @param _tokenId The NFT to transfer // /// @param data Additional data with no specified format, sent in call to `_to` // function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; // /// @notice Transfers the ownership of an NFT from one address to another address // /// @dev This works identically to the other function with an extra data parameter, // /// except this function just sets data to "" // /// @param _from The current owner of the NFT // /// @param _to The new owner // /// @param _tokenId The NFT to transfer // function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; // /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE // /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE // /// THEY MAY BE PERMANENTLY LOST // /// @dev Throws unless `msg.sender` is the current owner, an authorized // /// operator, or the approved address for this NFT. Throws if `_from` is // /// not the current owner. Throws if `_to` is the zero address. Throws if // /// `_tokenId` is not a valid NFT. // /// @param _from The current owner of the NFT // /// @param _to The new owner // /// @param _tokenId The NFT to transfer // function transferFrom(address _from, address _to, uint256 _tokenId) external payable; // /// @notice Set or reaffirm the approved address for an NFT // /// @dev The zero address indicates there is no approved address. // /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized // /// operator of the current owner. // /// @param _approved The new approved NFT controller // /// @param _tokenId The NFT to approve // function approve(address _approved, uint256 _tokenId) external payable; // /// @notice Enable or disable approval for a third party ("operator") to manage // /// all of `msg.sender`'s assets. // /// @dev Emits the ApprovalForAll event. The contract MUST allow // /// multiple operators per owner. // /// @param _operator Address to add to the set of authorized operators. // /// @param _approved True if the operator is approved, false to revoke approval // function setApprovalForAll(address _operator, bool _approved) external; // /// @notice Get the approved address for a single NFT // /// @dev Throws if `_tokenId` is not a valid NFT // /// @param _tokenId The NFT to find the approved address for // /// @return The approved address for this NFT, or the zero address if there is none // function getApproved(uint256 _tokenId) external view returns (address); // /// @notice Query if an address is an authorized operator for another address // /// @param _owner The address that owns the NFTs // /// @param _operator The address that acts on behalf of the owner // /// @return True if `_operator` is an approved operator for `_owner`, false otherwise // function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the /// recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return /// of other than the magic value MUST result in the transaction being reverted. /// @notice The contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } /// @dev use to pause contracts contract ScratchAccessControl { /// @dev This contract is used to pause contracts when necessary /// @dev address of admin address public adminAddress; /// @dev state of contracts bool public paused = false; /// @dev Access modifier for admin-only functionality modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /// @dev Set new admin function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } /// @dev Access modifier to control actions depends on paused state modifier whenPaused() { require(paused); _; } modifier whenNotPaused() { require(!paused); _; } /// @dev Only admin can control paused state function pause() external onlyAdmin whenNotPaused { paused = true; } function unpause() external onlyAdmin whenPaused { paused = false; } } /// @dev Base contract for scratch contract ScratchBase is ScratchAccessControl { /* EVENTS */ /// @dev Transfer events fired whenever a scratch bought by someone event Transfer(address from, address to, uint256 tokenId); /* DATA TYPES */ /// @dev Scratch struct struct Scratch { // time when this scratch be created uint64 createTime; // time when this scratch be bought uint64 boughtTime; // prize value of this scratch uint16 prizeValue; } /* CONSTANTS */ /* STORAGE */ // array to store all scratchs Scratch[] scratches; // array to store all unsold cards uint256 sold = 0; /// @dev Scratch id to owner address mapping (uint256 => address) public scratchIndexToOwner; /// @dev scratchs owned by one owner mapping (address => uint256) public ownershipTokenCount; /// @dev Assign ownership of a specific scratch card to an address function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; scratchIndexToOwner[_tokenId] = _to; // _from must be 0x0 in this scratch contract if (_from != address(0)) { revert(); } // Emit event // Transfer(_from, _to, _tokenId); } /// @dev Initialize scratch card /// @param _prizeValue Amount of prize displayed on card function _createCard(uint16 _prizeValue) internal returns (uint256) { Scratch memory _scratch = Scratch({ createTime: uint64(now), boughtTime: 0, prizeValue: uint16(_prizeValue) }); uint256 newScratchId = scratches.push(_scratch) - 1; return newScratchId; } } /// @dev Main function part of scratch card contract ScratchMain is ScratchBase, ERC721 { /// @dev Name and type of scratch card string public name; string public symbol; string public constant objectType = "scratch"; uint256 public totalSupply; uint16 public price; uint8 public prizePercentage; uint16 public prizeValue; /// @dev initialize function when this contract first being deployed /// @param _totalSupply is the number of total scratch cards /// @param _prizePercentage is the percentage of card with prize /// @param _prizeValue is the prize won in scratch card /// @param _name is the name of contract /// @param _symbol is the symbol of contract constructor ( uint256 _totalSupply, uint8 _prizePercentage, uint16 _prizeValue, uint16 _price, string _name, string _symbol ) public { // set name, symbol, and total scratch supply totalSupply = _totalSupply; name = _name; symbol = _symbol; price = _price; prizePercentage = _prizePercentage; prizeValue = _prizeValue; // set admin adminAddress = msg.sender; uint256 prizeNumber = uint256 ((uint256 (totalSupply * prizePercentage)) / 100); // initialize all totalSupply scratch cards uint i = totalSupply; uint j = prizeNumber; uint result; for ( ; i != 0; i--) { // create a random number uint random = uint(keccak256(abi.encodePacked(now, i, block.difficulty))) % 100; // if all cards not created have prize if (j != 0 && i == j) { // create card result = _createCard(prizeValue); j--; } else if (j != 0 && i > j) { // if not all cards have prize // approximately make prize cards satisfy the percentage if (random < prizePercentage) { result = _createCard(prizeValue); j--; } else { result = _createCard(0); } } else if (j == 0) { // if no prize left result = _createCard(0); } } } /// @dev check the number of cards owned by one address /// @param _owner the owner address function balanceOf(address _owner) public view returns (uint256) { return ownershipTokenCount[_owner]; } /// @dev check the total supply function totalSupply() public view returns (uint256) { // return totalSupply; return scratches.length; } /// @dev check the price of scratch card function price() public view returns (uint256) { return price; } /// @dev check the owner of scratch card /// @param _tokenId id of scratch card function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = scratchIndexToOwner[_tokenId]; // if card not sold require(owner != address(0)); } /// @dev get the number of sold scratch cards function getSold() public view returns (uint256) { return sold; } /// @dev get prize value on scratch card given id function prizeOf(uint256 _tokenId) external view returns (uint16) { return scratches[_tokenId].prizeValue; } /// @dev buy one card function buyScratch() external payable whenNotPaused returns (uint256) { // Avoid strange things happen require(msg.sender != address(0)); // check paid amount require(msg.value == price * (10 ** 18)); // check if all cards are sold out require(sold != totalSupply); // got it! scratches[sold].boughtTime = uint64(now); scratchIndexToOwner[sold] = msg.sender; ownershipTokenCount[msg.sender]++; sold++; // return sold; } /// @dev get all eth back function retrieveAllEth() external onlyAdmin { // get balance of contract uint256 amount = address(this).balance; // check balance require(amount > 0); // transfer all ehter msg.sender.transfer(amount); } }
check the price of scratch card
function price() public view returns (uint256) { return price; }
5,390,720
./partial_match/97/0xEa2adCDA71A7a408154bEe735BbC4a8F2E1b6232/sources/CryptoPesoStablecoin.sol
See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; }
11,491,405
./full_match/43114/0x7D168034C6073247bCdC4Ff9f7FC13b4eD6f76e8/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. valid ERC20 token
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate) external onlyOwner { require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval"); _lpToken.balanceOf(address(this)); require(_depositFeeBP <= 400, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardSecond = block.timestamp > startTime ? block.timestamp : startTime; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push( PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardSecond : lastRewardSecond, accSeedPerShare : 0, depositFeeBP : _depositFeeBP, harvestInterval: _harvestInterval, lpSupply: 0 }) ); emit addPool(poolInfo.length - 1, address(_lpToken), _allocPoint, _depositFeeBP, _harvestInterval); }
4,568,719
./partial_match/1/0xD59BcAbd00721B754aCB79FE668faE4B6A063fF8/sources/contracts/carbon/CarbonController.sol
pauses the CarbonController requirements: - the caller must have the ROLE_EMERGENCY_STOPPER privilege/
function pause() external onlyRoleMember(ROLE_EMERGENCY_STOPPER) { _pause(); }
2,647,178
./partial_match/570/0xf2ad472ade2009Ef5eeb26B7fe27BA9fd27dE46A/sources/contracts/L2/GasPriceOracle.sol
@custom:legacy Retrieves the number of decimals used in the scalar. return Number of decimals used in the scalar.
function decimals() public pure returns (uint256) { return DECIMALS; }
3,504,304
./full_match/11155111/0xc5b29a1C6b3ACD62F9359f2c16d6E9eD441092aa/sources/project_/contracts/TokenLogic.sol
Sets the fee for each mint and burn Requirements: - `fee` must be less than or equal to 1% (1000)/
function setMintAndBurnFee(uint256 fee) public virtual { require(fee <= MAX_FEE, "ERC20: fee must be less than or equal to 1%"); _mintAndBurnFee = fee; }
3,799,878
pragma solidity ^0.4.24; // File: node_modules/openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public; } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes data ) public returns(bytes4); } // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: node_modules/openzeppelin-solidity/contracts/utils/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: node_modules/openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkAndCallSafeTransfer(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor() public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) public view returns (string); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string internal _name; // Token symbol string internal _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor(string name, string symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) public view returns (string) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor(string name, string symbol) ERC721Metadata(name, symbol) public { } } // File: node_modules/openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: node_modules/openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() public { minters.add(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { minters.add(account); emit MinterAdded(account); } function renounceMinter() public { minters.remove(msg.sender); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol /** * @title ERC721Mintable * @dev ERC721 minting logic */ contract ERC721Mintable is ERC721Full, MinterRole { event MintingFinished(); bool private _mintingFinished = false; modifier onlyBeforeMintingFinished() { require(!_mintingFinished); _; } /** * @return true if the minting is finished. */ function mintingFinished() public view returns(bool) { return _mintingFinished; } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 tokenId ) public onlyMinter onlyBeforeMintingFinished returns (bool) { _mint(to, tokenId); return true; } function mintWithTokenURI( address to, uint256 tokenId, string tokenURI ) public onlyMinter onlyBeforeMintingFinished returns (bool) { mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyMinter onlyBeforeMintingFinished returns (bool) { _mintingFinished = true; emit MintingFinished(); return true; } } // File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/test.sol contract MyTokenCollection is ERC721Full,ERC721Mintable,Ownable { constructor() public ERC721Full("MyTokenCollection", "MTC") {} function mintTokenCollection(string _tokenURI) public { uint256 newTokenId = _getNextTokenId(); _mint(msg.sender, newTokenId); _setTokenURI(newTokenId, _tokenURI); } function _getNextTokenId() private view returns (uint256) { return totalSupply().add(1); } function _setTokenURI(uint256 _tokenId, string _uri) internal { require(_exists(_tokenId)); super._setTokenURI(_tokenId, _uri); } }
Internal function to add a token ID to the list of a given address to address representing the new owner of the given token ID tokenId uint256 ID of the token to be added to the tokens list of the given address/
function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; }
538,544