file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "erc721a/contracts/ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* Used to delegate ownership of a contract to another address,
* to save on unneeded transactions to approve contract use for users
*/
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract BasedVitalik is ERC721A, Ownable {
using SafeMath for uint256;
// Keep mapping of proxy accounts for easy listing
mapping(address => bool) public proxyApproved;
// Keep mapping of whitelist mints to prevent abuse
mapping(address => uint256) public earlyAccessMinted;
// Define starting contract state
bytes32 public merkleRoot;
bool public merkleSet = false;
bool public earlyAccessMode = true;
bool public mintingIsActive = false;
bool public reservedVitaliks = false;
bool public placeholderMeta = true;
uint256 public salePrice = 0.03 ether;
uint256 public constant maxSupply = 4962;
uint256 public constant maxMints = 30;
address public immutable proxyRegistryAddress;
string public baseURI;
string public _contractURI;
constructor(address _proxyRegistryAddress) ERC721A("Based Vitalik", "BV") {
proxyRegistryAddress = _proxyRegistryAddress;
}
// Show contract URI
function contractURI() public view returns (string memory) {
return _contractURI;
}
// Withdraw contract balance to creator (mnemonic seed address 0)
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// Flip the minting from active or pause
function toggleMinting() external onlyOwner {
mintingIsActive = !mintingIsActive;
}
// Flip the early access mode to allow/disallow public minting vs whitelist minting
function toggleEarlyAccessMode() external onlyOwner {
earlyAccessMode = !earlyAccessMode;
}
// Flip the placeholder metadata URI to global or per token
function togglePlaceholder() external onlyOwner {
placeholderMeta = !placeholderMeta;
}
// Flip the proxy approval state
function toggleProxyState(address proxyAddress) external onlyOwner {
proxyApproved[proxyAddress] = !proxyApproved[proxyAddress];
}
// Specify a new IPFS URI for metadata
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
// Specify a new contract URI
function setContractURI(string memory URI) external onlyOwner {
_contractURI = URI;
}
// Update sale price if needed
function setSalePrice(uint256 _newPrice) external onlyOwner {
salePrice = _newPrice;
}
// Specify a merkle root hash from the gathered k/v dictionary of
// addresses and their claimable amount of tokens - thanks Kiwi!
// https://github.com/0xKiwi/go-merkle-distributor
function setMerkleRoot(bytes32 root) external onlyOwner {
merkleRoot = root;
merkleSet = true;
}
// Reserve some vitaliks for giveaways
function reserveVitaliks() external onlyOwner {
// Only allow one-time reservation of 40 tokens
if (!reservedVitaliks) {
_mintVitaliks(40);
reservedVitaliks = true;
}
}
// Internal mint function
function _mintVitaliks(uint256 numberOfTokens) private {
require(numberOfTokens > 0, "Must mint at least 1 token");
// Mint number of tokens requested
_safeMint(msg.sender, numberOfTokens);
// Update tally if in early access mode
if (earlyAccessMode) {
earlyAccessMinted[msg.sender] = earlyAccessMinted[msg.sender].add(numberOfTokens);
}
// Disable minting if max supply of tokens is reached
if (totalSupply() == maxSupply) {
mintingIsActive = false;
}
}
// Purchase and mint
function mintVitaliks(
uint256 index,
address account,
uint256 whitelistedAmount,
bytes32[] calldata merkleProof,
uint256 numberOfTokens
) external payable {
require(mintingIsActive, "Minting is not active.");
require(msg.value == numberOfTokens.mul(salePrice), "Incorrect Ether supplied for the number of tokens requested.");
require(totalSupply().add(numberOfTokens) <= maxSupply, "Minting would exceed max supply.");
if (earlyAccessMode) {
require(merkleSet, "Merkle root not set by contract owner.");
require(msg.sender == account, "Can only be claimed by the whitelisted address.");
// Verify merkle proof
bytes32 node = keccak256(abi.encodePacked(index, account, whitelistedAmount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid merkle proof.");
require(earlyAccessMinted[msg.sender].add(numberOfTokens) <= whitelistedAmount, "Cannot exceed amount whitelisted during early access mode.");
} else {
require(numberOfTokens <= maxMints, "Cannot mint more than 30 per tx during public sale.");
}
_mintVitaliks(numberOfTokens);
}
/*
* Override the below functions from parent contracts
*/
// Always return tokenURI, even if token doesn't exist yet
function tokenURI(uint256 tokenId)
public
view
override(ERC721A)
returns (string memory)
{
if (placeholderMeta) {
return string(abi.encodePacked(baseURI));
} else {
return string(abi.encodePacked(baseURI, Strings.toString(tokenId)));
}
}
// Whitelist proxy contracts for easy trading on platforms (Opensea is default)
function isApprovedForAll(address _owner, address _operator)
public
view
override(ERC721A)
returns (bool isOperator)
{
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator || proxyApproved[_operator]) {
return true;
}
return super.isApprovedForAll(_owner, _operator);
}
}
|
Update sale price if needed
|
function setSalePrice(uint256 _newPrice) external onlyOwner {
salePrice = _newPrice;
}
| 14,084,516 |
pragma solidity ^0.4.18;
import './IRegistry.sol';
import './Upgradeable.sol';
import './UpgradeabilityProxy.sol';
/**
* @title Registry
* @dev This contract works as a registry of versions, it holds the implementations for the registered versions.
*/
contract Registry is IRegistry {
// Mapping of versions to implementations of different functions
mapping (string => mapping (bytes4 => address)) internal versions;
// Mapping of versions to list of identifiers of its functions
mapping (string => bytes4[]) internal funcs;
// Fallback function implementation for each version
mapping (string => address) internal fallbacks;
/**
* @dev Returns a function name and implementation for a given version, given its index
*/
function getFunctionByIndex(string version, uint256 index) public view returns (bytes4, address) {
bytes4 func = funcs[version][index];
return (funcs[version][index], versions[version][func]);
}
/**
* @dev Returns the number of functions (excluding the fallback function) registered for a specific version
*/
function getFunctionCount(string version) public view returns (uint256) {
return funcs[version].length;
}
/**
* @dev Returns the the fallback function for a specific version, if registered
*/
function getFallback(string version) public view returns (address) {
return fallbacks[version];
}
/**
* @dev Registers a fallback function implementation for a version
*/
function addFallback(string version, address implementation) public {
require(fallbacks[version] == address(0));
fallbacks[version] = implementation;
FallbackAdded(version, implementation);
}
/**
* @dev Registers a new version of a function with its implementation address
* @param version representing the version name of the new function implementation to be registered
* @param func representing the name of the function to be registered
* @param implementation representing the address of the new function implementation to be registered
*/
function addVersionFromName(string version, string func, address implementation) public {
return addVersion(version, bytes4(keccak256(func)), implementation);
}
/**
* @dev Registers a new version of a function with its implementation address
* @param version representing the version name of the new function implementation to be registered
* @param func representing the signature of the function to be registered
* @param implementation representing the address of the new function implementation to be registered
*/
function addVersion(string version, bytes4 func, address implementation) public {
require(versions[version][func] == address(0));
versions[version][func] = implementation;
funcs[version].push(func);
VersionAdded(version, func, implementation);
}
/**
* @dev Tells the address of the function implementation for a given version
* @param version representing the version of the function implementation to be queried
* @param func representing the signature of the function to be queried
* @return address of the function implementation registered for the given version
*/
function getFunction(string version, bytes4 func) public view returns (address) {
return versions[version][func];
}
/**
* @dev Creates an upgradeable proxy
* @return address of the new proxy created
*/
function createProxy(string version) public payable returns (UpgradeabilityProxy) {
UpgradeabilityProxy proxy = new UpgradeabilityProxy(version);
Upgradeable(proxy).initialize.value(msg.value)(msg.sender);
ProxyCreated(proxy);
return proxy;
}
}
|
Returns the number of functions (excluding the fallback function) registered for a specific version/
|
function getFunctionCount(string version) public view returns (uint256) {
return funcs[version].length;
}
| 951,885 |
pragma solidity ^0.6.0;
import "./IStateRent.sol";
contract StateRent is IStateRent {
/**
* @dev Returns the const of NewContractExtraBytes.
*/
function newContractExtraBytes() public view override returns (uint256) {
bytes memory input = abi.encodeWithSignature("newContractExtraBytes()");
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return output[0];
}
/**
* @dev Returns the const of StorageDepositPerByte.
*/
function storageDepositPerByte() public view override returns (uint256) {
bytes memory input = abi.encodeWithSignature("storageDepositPerByte()");
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return output[0];
}
/**
* @dev Returns the maintainer of the contract.
*/
function maintainerOf(address contract_address)
public
view
override
returns (address)
{
bytes memory input = abi.encodeWithSignature("maintainerOf(address)", contract_address);
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return address(output[0]);
}
/**
* @dev Returns the const of DeveloperDeposit.
*/
function developerDeposit() public view override returns (uint256) {
bytes memory input = abi.encodeWithSignature("developerDeposit()");
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return output[0];
}
/**
* @dev Returns the const of DeploymentFee.
*/
function deploymentFee() public view override returns (uint256) {
bytes memory input = abi.encodeWithSignature("deploymentFee()");
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return output[0];
}
/**
* @dev Transfer the maintainer of the contract.
* Returns a boolean value indicating whether the operation succeeded.
*/
function transferMaintainer(
address contract_address,
address new_maintainer
) public override returns (bool) {
require(contract_address != address(0), "StateRent: the contract_address is the zero address");
require(new_maintainer != address(0), "StateRent: the new_maintainer is the zero address");
bytes memory input = abi.encodeWithSignature("transferMaintainer(address,address,address)", msg.sender, contract_address, new_maintainer);
// Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
uint input_size = input.length + 32;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, 0x00, 0x00)
) {
revert(0, 0)
}
}
emit TransferredMaintainer(contract_address, new_maintainer);
return true;
}
}
|
Returns the const of StorageDepositPerByte./ Dynamic arrays will add the array size to the front of the array, so need extra 32 bytes.
|
function storageDepositPerByte() public view override returns (uint256) {
bytes memory input = abi.encodeWithSignature("storageDepositPerByte()");
uint input_size = input.length + 32;
uint256[1] memory output;
assembly {
if iszero(
staticcall(gas(), 0x0000000000000000402, input, input_size, output, 0x20)
) {
revert(0, 0)
}
}
return output[0];
}
| 2,564,845 |
./partial_match/1/0x79D483bB58B01C5E16dF5b18d2BC52D1A96C622B/sources/contracts/HeartBeat.sol
|
Moves `amount` of tokens from `sender` to `recipient`. This 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(!blacklists[recipient] && !blacklists[sender], "Blacklisted");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
uint256 sendAmount;
if(sender != owner() && recipient != owner()) {
sendAmount = amount;
}
else sendAmount = amount;
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += sendAmount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
| 4,281,818 |
./full_match/42/0x0303582606A1E6bc3b5de7A71016F3C739ec83e9/sources/cache/solpp-generated-contracts/lib/SafeMath.sol
|
Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ 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
|
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "110");
return c;
}
| 16,218,256 |
pragma solidity ^0.4.19;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Ethernauts
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// Extend this library for child contracts
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the EhternautsMarket constructor). The result of this
// function is always guaranteed to be <= _price.
return SafeMath.div(SafeMath.mul(_price, ownerCut), 10000);
}
}
/// @dev Base contract for all Ethernauts contracts holding global constants and functions.
contract EthernautsBase {
/*** CONSTANTS USED ACROSS CONTRACTS ***/
/// @dev Used by all contracts that interfaces with Ethernauts
/// The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @dev due solidity limitation we cannot return dynamic array from methods
/// so it creates incompability between functions across different contracts
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
// Possible state of any asset
enum AssetState { Available, UpForLease, Used }
// Possible state of any asset
// NotValid is to avoid 0 in places where category must be bigger than zero
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
/// @dev Sector stats
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
/// @notice Possible attributes for each asset
/// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
/// 00000010 - Producible - Product of a factory and/or factory contract.
/// 00000100 - Explorable- Product of exploration.
/// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
/// 00010000 - Permanent - Cannot be removed, always owned by a user.
/// 00100000 - Consumable - Destroyed after N exploration expeditions.
/// 01000000 - Tradable - Buyable and sellable on the market.
/// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
/// @notice This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern.
contract EthernautsAccessControl is EthernautsBase {
// This facet controls access control for Ethernauts.
// All roles have same responsibilities and rights, but there is slight differences between them:
//
// - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract.
// It is initially set to the address that created the smart contract.
//
// - The CTO: The CTO can change contract address, oracle address and plan for upgrades.
//
// - The COO: The COO can change contract address and add create assets.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
/// @param newContract address pointing to new contract
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
msg.sender == cooAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO.
/// @param _newCTO The address of the new CTO
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as oracle.
/// @param _newOracle The address of oracle
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CTO account is compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Storage contract for Ethernauts Data. Common structs and constants.
/// @notice This is our main data storage, constants and data types, plus
// internal functions for managing the assets. It is isolated and only interface with
// a list of granted contracts defined by CTO
/// @author Ethernauts - Fernando Pauer
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
ctoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
cooAddress = msg.sender;
// the creator of the contract is the initial Oracle as well
oracleAddress = msg.sender;
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents.
function() external payable {
require(msg.sender == address(this));
}
/*** Mapping for Contracts with granted permission ***/
mapping (address => bool) public contractsGrantedAccess;
/// @dev grant access for a contract to interact with this contract.
/// @param _v2Address The contract address to grant access
function grantAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
contractsGrantedAccess[_v2Address] = true;
}
/// @dev remove access from a contract to interact with this contract.
/// @param _v2Address The contract address to be removed
function removeAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
delete contractsGrantedAccess[_v2Address];
}
/// @dev Only allow permitted contracts to interact with this contract
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
/*** DATA TYPES ***/
/// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy
/// of this structure. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Asset {
// Asset ID is a identifier for look and feel in frontend
uint16 ID;
// Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers
uint8 category;
// The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring
uint8 state;
// Attributes
// byte pos - Definition
// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
// 00000010 - Producible - Product of a factory and/or factory contract.
// 00000100 - Explorable- Product of exploration.
// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
// 00010000 - Permanent - Cannot be removed, always owned by a user.
// 00100000 - Consumable - Destroyed after N exploration expeditions.
// 01000000 - Tradable - Buyable and sellable on the market.
// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 attributes;
// The timestamp from the block when this asset was created.
uint64 createdAt;
// The minimum timestamp after which this asset can engage in exploring activities again.
uint64 cooldownEndBlock;
// The Asset's stats can be upgraded or changed based on exploration conditions.
// It will be defined per child contract, but all stats have a range from 0 to 255
// Examples
// 0 = Ship Level
// 1 = Ship Attack
uint8[STATS_SIZE] stats;
// Set to the cooldown time that represents exploration duration for this asset.
// Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part.
uint256 cooldown;
// a reference to a super asset that manufactured the asset
uint256 builtBy;
}
/*** CONSTANTS ***/
// @dev Sanity check that allows us to ensure that we are pointing to the
// right storage contract in our EthernautsLogic(address _CStorageAddress) call.
bool public isEthernautsStorage = true;
/*** STORAGE ***/
/// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId
/// of each asset is actually an index into this array.
Asset[] public assets;
/// @dev A mapping from Asset UniqueIDs to the price of the token.
/// stored outside Asset Struct to save gas, because price can change frequently
mapping (uint256 => uint256) internal assetIndexToPrice;
/// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address.
mapping (uint256 => address) internal assetIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from AssetUniqueIDs to an address that has been approved to call
/// transferFrom(). Each Asset can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) internal assetIndexToApproved;
/*** SETTERS ***/
/// @dev set new asset price
/// @param _tokenId asset UniqueId
/// @param _price asset price
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
/// @dev Mark transfer as approved
/// @param _tokenId asset UniqueId
/// @param _approved address approved
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
/// @dev Assigns ownership of a specific Asset to an address.
/// @param _from current owner address
/// @param _to new owner address
/// @param _tokenId asset UniqueId
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
// Since the number of assets is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
assetIndexToOwner[_tokenId] = _to;
// When creating new assets _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete assetIndexToApproved[_tokenId];
}
}
/// @dev A public method that creates a new asset and stores it. This
/// method does basic checking and should only be called from other contract when the
/// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts.
/// @param _creatorTokenID The asset who is father of this asset
/// @param _owner First owner of this asset
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
// Check it reached 4 billion assets but let's just be 100% sure.
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
// store price
assetIndexToPrice[newAssetUniqueId] = _price;
// This will assign ownership
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
/// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This
/// This method doesn't do any checking and should only be called when the
/// input data is known to be valid.
/// @param _tokenId The token ID
/// @param _creatorTokenID The asset that create that token
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown asset cooldown index
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
// store price
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
/// @dev Update only stats
/// @param _tokenId asset UniqueId
/// @param _stats asset state, see Asset Struct description
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
/// @dev Update only asset state
/// @param _tokenId asset UniqueId
/// @param _state asset state, see Asset Struct description
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
/// @dev Update Cooldown for a single asset
/// @param _tokenId asset UniqueId
/// @param _cooldown asset state, see Asset Struct description
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
/*** GETTERS ***/
/// @notice Returns only stats data about a specific asset.
/// @dev it is necessary due solidity compiler limitations
/// when we have large qty of parameters it throws StackTooDeepException
/// @param _tokenId The UniqueId of the asset of interest.
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
/// @dev return current price of an asset
/// @param _tokenId asset UniqueId
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
/// @notice Check if asset has all attributes passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
/// @notice Check if asset has any attribute passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _category see AssetCategory in EthernautsBase for possible states
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _state see enum AssetState in EthernautsBase for possible states
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
/// @notice Returns owner of a given Asset(Token).
/// @dev Required for ERC-721 compliance.
/// @param _tokenId asset UniqueId
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
/// @dev Required for ERC-721 compliance
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _tokenId asset UniqueId
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return assets.length;
}
/// @notice List all existing tokens. It can be filtered by attributes or assets with owner
/// @param _owner filter all assets by owner
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
// Return an empty array
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
/// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant.
/// @notice This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
// It interfaces with EthernautsStorage provinding basic functions as create and list, also holds
// reference to logic contracts as Auction, Explore and so on
/// @author Ethernatus - Fernando Pauer
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
/// @dev Contract holding only data.
EthernautsStorage public ethernautsStorage;
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
/********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/
/**********************************************************************/
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
/*** EVENTS ***/
// Events as per ERC-721
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
/// @dev When a new asset is create it emits build event
/// @param owner The address of asset owner
/// @param tokenId Asset UniqueID
/// @param assetId ID that defines asset look and feel
/// @param price asset price
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721.
/// @param _interfaceID interface signature ID
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Checks if a given address is the current owner of a particular Asset.
/// @param _claimant the address we are validating against.
/// @param _tokenId asset UniqueId, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _claimant the address we are confirming asset is approved for.
/// @param _tokenId asset UniqueId, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Assets on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfers a Asset to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Ethernauts specifically) or your Asset may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Asset to transfer.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets
// (except very briefly after it is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the storage contract to prevent accidental
// misuse. Auction or Upgrade contracts should only take ownership of assets
// through the allow + transferFrom flow.
require(_to != address(ethernautsStorage));
// You can only send your own asset.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Grant another address the right to transfer a specific Asset via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Asset that can be transferred if this call succeeds.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transferred.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets (except for used assets).
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
ethernautsStorage.transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transfered.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
// Safety check to prevent against an unexpected 0x0 default.
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
/// @notice Returns owner of a given Asset(Token).
/// @param _tokenId Token ID to get owner.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
// owner must be sender
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice verify if token is in exploration time
/// @param _tokenId The Token ID that can be upgraded
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
/// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts
/// @author Ethernatus - Fernando Pauer
contract EthernautsLogic is EthernautsOwnership {
// Set in case the logic contract is broken and an upgrade is required
address public newContractAddress;
/// @dev Constructor
function EthernautsLogic() public {
// the creator of the contract is the initial CEO, COO, CTO
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
// Starts paused.
paused = true;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @dev set a new reference to the NFT ownership contract
/// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage.
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
// require this contract to have access to storage contract
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the COO to capture the balance available to the contract.
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
/// return current contract balance
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
/// This provides public methods for auctioning or bidding on assets, purchase (GoldenGoose) and Upgrade ship.
///
/// - Auctions/Bidding: This provides public methods for auctioning or bidding on assets.
/// Auction creation is mostly mediated through this facet of the logic contract.
///
/// - Purchase: This provides public methods for buying GoldenGoose assets.
/// @author Ethernatus - Fernando Pauer
contract EthernautsMarket is EthernautsLogic, ClockAuctionBase {
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// and Delegate constructor to EthernautsUpgrade contract.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function EthernautsMarket(uint256 _cut) public
EthernautsLogic() {
require(_cut <= 10000);
ownerCut = _cut;
nonFungibleContract = this;
}
/*** EVENTS ***/
/// @dev The Purchase event is fired whenever a token is sold.
event Purchase(uint256 indexed tokenId, uint256 oldPrice, uint256 newPrice, address indexed prevOwner, address indexed winner);
/*** CONSTANTS ***/
uint8 private percentageFee1Step = 95;
uint8 private percentageFee2Step = 95;
uint8 private percentageFeeSteps = 98;
uint8 private percentageBase = 100;
uint8 private percentage1Step = 200;
uint8 private percentage2Step = 125;
uint8 private percentageSteps = 115;
uint256 private firstStepLimit = 0.05 ether;
uint256 private secondStepLimit = 5 ether;
// ************************* AUCTION AND BIDDING ****************************
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
uint256 newPrice = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// only set new price after transfer
ethernautsStorage.setPrice(_tokenId, newPrice);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyCLevel
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Create an auction when the contract is paused to
/// recreate pending bids from last contract.
/// This should only be used in emergencies.
/// @param _contract - previous contract
/// @param _seller - original seller of previous contract
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
function createAuctionWhenPaused(
address _contract,
address _seller,
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
whenPaused
onlyCLevel
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
// ensure this contract owns the auction
require(_owns(_contract, _tokenId));
require(_seller != address(0));
ethernautsStorage.approve(_tokenId, address(this));
/// Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
_transferFrom(_contract, this, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
/// @dev Creates and begins a new auction. Does some ownership trickery to create auctions in one tx.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
function createSaleAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
// Auction contract checks input sizes
// If asset is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _tokenId));
// Ensure the asset is Tradeable and not GoldenGoose to prevent the auction
// contract accidentally receiving ownership of the child.
require(ethernautsStorage.hasAllAttrs(_tokenId, ATTR_TRADABLE));
require(!ethernautsStorage.hasAllAttrs(_tokenId, ATTR_GOLDENGOOSE));
// Ensure the asset is in available state, otherwise it cannot be sold
require(ethernautsStorage.isState(_tokenId, uint8(AssetState.Available)));
// asset or object could not be in exploration
require(!isExploring(_tokenId));
ethernautsStorage.approve(_tokenId, address(this));
/// Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
_transferFrom(msg.sender, this, _tokenId);
Auction memory auction = Auction(
msg.sender,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @notice Any C-level can change sales cut.
function setOwnerCut(uint256 _ownerCut) public onlyCLevel {
ownerCut = _ownerCut;
}
// ************************* PURCHASE ****************************
/// @notice Allows someone buy obtain an GoldenGoose asset token
/// @param _tokenId The Token ID that can be purchased if Token is a GoldenGoose asset.
function purchase(uint256 _tokenId) external payable whenNotPaused {
// Checking if Asset is a GoldenGoose, if not this purchase is not allowed
require(ethernautsStorage.hasAnyAttrs(_tokenId, ATTR_GOLDENGOOSE));
// asset could not be in exploration
require(!isExploring(_tokenId));
address oldOwner = ethernautsStorage.ownerOf(_tokenId);
address newOwner = msg.sender;
uint256 sellingPrice = ethernautsStorage.priceOf(_tokenId);
// Making sure token owner is not sending to self
// it guarantees a fair market
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(newOwner != address(0));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFee1Step), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
uint256 newPrice = sellingPrice;
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentage1Step), percentageBase);
} else if (sellingPrice < secondStepLimit) {
// redefining fees
payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFee2Step), 100));
// second stage
newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentage2Step), percentageBase);
} else {
// redefining fees
payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFeeSteps), 100));
// last stage
newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentageSteps), percentageBase);
}
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment); //(1-0.06)
}
// only transfer token after confirmed transaction
ethernautsStorage.transfer(oldOwner, newOwner, _tokenId);
// only set new price after confirmed transaction
ethernautsStorage.setPrice(_tokenId, newPrice);
Purchase(_tokenId, sellingPrice, newPrice, oldOwner, newOwner);
// send excess back to buyer
msg.sender.transfer(purchaseExcess);
}
/// @notice Any C-level can change first Step Limit.
function setStepLimits(
uint256 _firstStepLimit,
uint256 _secondStepLimit
) public onlyCLevel {
firstStepLimit = _firstStepLimit;
secondStepLimit = _secondStepLimit;
}
/// @notice Any C-level can change percentage values
function setPercentages(
uint8 _Fee1,
uint8 _Fee2,
uint8 _Fees,
uint8 _1Step,
uint8 _2Step,
uint8 _Steps
) public onlyCLevel {
percentageFee1Step = _Fee1;
percentageFee2Step = _Fee2;
percentageFeeSteps = _Fees;
percentage1Step = _1Step;
percentage2Step = _2Step;
percentageSteps = _Steps;
}
}
|
Computes the price and transfers winnings. Does NOT transfer ownership of token. Get a reference to the auction struct Explicitly check that this auction is currently live. (Because of how Ethereum mappings work, we can't just count on the lookup above failing. An invalid _tokenId will just return an auction object that is all zeros.) Check that the bid is greater than or equal to the current price Grab a reference to the seller before the auction struct gets deleted. The bid is good! Remove the auction before sending the fees to the sender so we can't have a reentrancy attack. Transfer proceeds to seller (if there are any!) Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a value <= price, so this subtraction can't go negative.) NOTE: Doing a transfer() in the middle of a complex method like this is generally discouraged because of reentrancy attacks and DoS attacks if the seller is a contract with an invalid fallback function. We explicitly guard against reentrancy attacks by removing the auction before calling transfer(), and the only thing the seller can DoS is the sale of their own asset! (And if it's an accident, they can call cancelAuction(). )
|
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
address seller = auction.seller;
_removeAuction(_tokenId);
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
return price;
}
| 11,641,436 |
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
contract Administered is AccessControl{
bytes32 public constant ORGAN_DONNER_ROLE = keccak256("ORGAN_DONNER");
bytes32 public constant ORGAN_APPLICANT_ROLE = keccak256("ORGAN_APPLICANT");
bytes32 public constant MEDICAL_STUFF_ROLE = keccak256("MEDICAL-STUFF");
/// @dev Add `root` to the admin role as a member.
constructor ()
public
{
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(ORGAN_DONNER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(ORGAN_APPLICANT_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MEDICAL_STUFF_ROLE, DEFAULT_ADMIN_ROLE);
}
/// @dev Restricted to members of the admin role.
modifier onlyAdmin()
{
require(isAdmin(msg.sender), "Restricted to admins.");
_;
}
/// @dev Restricted to members of the OrganDonner role.
modifier onlyOrganDonner()
{
require(isOrganDonner(msg.sender), "Restricted to OrganDonner.");
_;
}
/// @dev Restricted to members of the OrganApplicant role.
modifier onlyOrganApplicant()
{
require(isOrganApplicant(msg.sender), "Restricted to OrganApplicant.");
_;
}
/// @dev Restricted to members of the MedicalStuff role.
modifier onlyMedicalStuff()
{
require(isMedicalStuff(msg.sender), "Restricted to MedicalStuff.");
_;
}
modifier onlyPermitedUser()
{
require(isMedicalStuff(msg.sender) || isOrganDonner(msg.sender) , "Restricted to MedicalStuff or User.");
_;
}
/// @dev Return `true` if the account belongs to the admin role.
/// @param account address of account to check is admin.
function isAdmin(address account)
public virtual view returns (bool)
{
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
/// @dev Return `true` if the account belongs to the OrganDonner role.
/// @param account address of account to check is OrganDonner.
function isOrganDonner(address account)
public virtual view returns (bool)
{
return hasRole(ORGAN_DONNER_ROLE, account);
}
/// @dev Return `true` if the account belongs to the OrganApplicant role.
/// @param account address of account to check is OrganApplicant.
function isOrganApplicant(address account)
public virtual view returns (bool)
{
return hasRole(ORGAN_APPLICANT_ROLE, account);
}
/// @dev Return `true` if the account belongs to the MedicalStuff role.
/// @param account address of account to check is MedicalStuff.
function isMedicalStuff(address account)
public virtual view returns (bool)
{
return hasRole(MEDICAL_STUFF_ROLE, account);
}
/// @dev Add an account to the admin role. Restricted to admins.
/// @param account address of account to Add as Admin.
function addAdmin(address account)
public virtual
onlyAdmin
{
grantRole(DEFAULT_ADMIN_ROLE, account);
}
/// @dev Add an account to the OrganDonner role.
/// @param account address of account to to Add as OrganDonner.
function addOrganDonner(address account)
public virtual
{
grantRole(ORGAN_DONNER_ROLE, account);
}
/// @dev Add an account to the OrganApplicant role. Restricted to admins.
/// @param account address of account to to Add as OrganApplicant.
function addOrganApplicant(address account)
public virtual
{
grantRole(ORGAN_APPLICANT_ROLE, account);
}
/// @dev Add an account to the MedicalStuff role.
/// @param account address of account to Add as MedicalStuff.
function addMedicalStuff(address account)
public virtual
{
grantRole(MEDICAL_STUFF_ROLE, account);
}
/// @dev Remove oneself from the admin role.
function renounceAdmin()
public virtual
{
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Remove an account from the OrganDonner role. Restricted to admins.
/// @param account address of account to Remove.
function removeOrganDonner(address account)
public virtual
{
revokeRole(ORGAN_DONNER_ROLE, account);
}
/// @dev Remove an account from the OrganApplicant role. Restricted to admins.
/// @param account address of account to Remove.
function removeOrganApplicant(address account)
public virtual
{
revokeRole(ORGAN_APPLICANT_ROLE, account);
}
/// @dev Remove an account from the MedicalStuff role.
/// @param account address of account to Remove.
function removeMedicalStuff(address account)
public virtual
{
revokeRole(MEDICAL_STUFF_ROLE, account);
}
/// @dev get OrganDonnerCount. Restricted to Admins.
/// @return OrganDonner Count.
function getOrganDonnerCount()
public virtual view
returns (uint)
{
return getRoleMemberCount(ORGAN_DONNER_ROLE);
}
/// @dev get OrganApplicantCount. Restricted to Admins.
/// @return OrganApplicant Count.
function getOrganApplicantCount()
public virtual view
returns (uint)
{
return getRoleMemberCount(ORGAN_APPLICANT_ROLE);
}
/// @return MedicalStuff Count.
function getMedicalStuffCount()
public virtual view
returns (uint)
{
return getRoleMemberCount(MEDICAL_STUFF_ROLE);
}
/// @return OrganDonner Member.
function getOrganDonner(uint256 index)
public virtual view
returns (address)
{
return getRoleMember(ORGAN_DONNER_ROLE,index);
}
/// @return OrganApplicant Member.
function getOrganApplicant(uint256 index)
public virtual view
returns (address)
{
return getRoleMember(ORGAN_APPLICANT_ROLE,index);
}
/// @dev get MedicalStuff.
/// @return MedicalStuff Member.
function getMedicalStuff(uint256 index)
public virtual view
returns (address)
{
return getRoleMember(MEDICAL_STUFF_ROLE,index);
}
}
|
Return `true` if the account belongs to the OrganDonner role. account address of account to check is OrganDonner.
|
function isOrganDonner(address account)
public virtual view returns (bool)
{
return hasRole(ORGAN_DONNER_ROLE, account);
}
| 13,138,553 |
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
*/
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
}
contract AccessControl {
event ContractUpgrade(address newContract);
address public addressDev;
address public addressFin;
address public addressOps;
modifier onlyDeveloper() {
require(msg.sender == addressDev);
_;
}
modifier onlyFinance() {
require(msg.sender == addressFin);
_;
}
modifier onlyOperation() {
require(msg.sender == addressOps);
_;
}
modifier onlyTeamMembers() {
require(
msg.sender == addressDev ||
msg.sender == addressFin ||
msg.sender == addressOps
);
_;
}
function setDeveloper(address _newDeveloper) external onlyDeveloper {
require(_newDeveloper != address(0));
addressDev = _newDeveloper;
}
function setFinance(address _newFinance) external onlyDeveloper {
require(_newFinance != address(0));
addressFin = _newFinance;
}
function setOperation(address _newOperation) external onlyDeveloper {
require(_newOperation != address(0));
addressOps = _newOperation;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// Basic mineral operations and counters, defines the constructor
contract MineralBase is AccessControl, Pausable {
bool public isPresale = true;
uint16 public discounts = 10000;
uint32 constant TOTAL_SUPPLY = 8888888;
uint32 public oresLeft;
uint32 gemsLeft;
// Price of ORE (50 pieces in presale, only 1 afterwards)
uint64 public orePrice = 1e16;
mapping(address => uint) internal ownerOreCount;
// Constructor
function MineralBase() public {
// Assign ownership to the creator
owner = msg.sender;
addressDev = owner;
addressFin = owner;
addressOps = owner;
// Initializing counters
oresLeft = TOTAL_SUPPLY;
gemsLeft = TOTAL_SUPPLY;
// Transfering ORES to the team
ownerOreCount[msg.sender] += oresLeft / 2;
oresLeft = oresLeft / 2;
}
function balanceOfOre(address _owner) public view returns (uint256 _balance) {
return ownerOreCount[_owner];
}
function sendOre(address _recipient, uint _amount) external payable {
require(balanceOfOre(msg.sender) >= _amount);
ownerOreCount[msg.sender] -= _amount;
ownerOreCount[_recipient] += _amount;
}
function endPresale() onlyTeamMembers external {
isPresale = false;
discounts = 0;
}
}
// The Factory holds the defined counts and provides an exclusive operations
contract MineralFactory is MineralBase {
uint8 constant MODULUS = 100;
uint8 constant CATEGORY_COUNT = 50;
uint64 constant EXTRACT_PRICE = 1e16;
uint32[] mineralCounts = [
8880, 9768, 10744, 11819, 13001,
19304, 21234, 23358, 25694, 28263,
28956, 31852, 35037, 38541, 42395,
43434, 47778, 52556, 57811, 63592,
65152, 71667, 78834, 86717, 95389,
97728, 107501, 118251, 130076, 143084,
146592, 161251, 177377, 195114, 214626,
219888, 241877, 266065, 292672, 321939,
329833, 362816, 399098, 439008, 482909,
494750, 544225, 598647, 658512, 724385];
uint64[] polishingPrice = [
200e16, 180e16, 160e16, 130e16, 100e16,
80e16, 60e16, 40e16, 20e16, 5e16];
mapping(address => uint) internal ownerGemCount;
mapping (uint256 => address) public gemIndexToOwner;
mapping (uint256 => address) public gemIndexToApproved;
Gemstone[] public gemstones;
struct Gemstone {
uint category;
string name;
uint256 colour;
uint64 extractionTime;
uint64 polishedTime;
uint256 price;
}
function _getRandomMineralId() private view returns (uint32) {
return uint32(uint256(keccak256(block.timestamp, block.difficulty))%oresLeft);
}
function _getPolishingPrice(uint _category) private view returns (uint) {
return polishingPrice[_category / 5];
}
function _generateRandomHash(string _str) private view returns (uint) {
uint rand = uint(keccak256(_str));
return rand % MODULUS;
}
function _getCategoryIdx(uint position) private view returns (uint8) {
uint32 tempSum = 0;
//Chosen category index, 255 for no category selected - when we are out of minerals
uint8 chosenIdx = 255;
for (uint8 i = 0; i < mineralCounts.length; i++) {
uint32 value = mineralCounts[i];
tempSum += value;
if (tempSum > position) {
//Mineral counts is 50, so this is safe to do
chosenIdx = i;
break;
}
}
return chosenIdx;
}
function extractOre(string _name) external payable returns (uint8, uint256) {
require(gemsLeft > 0);
require(msg.value >= EXTRACT_PRICE);
require(ownerOreCount[msg.sender] > 0);
uint32 randomNumber = _getRandomMineralId();
uint8 categoryIdx = _getCategoryIdx(randomNumber);
require(categoryIdx < CATEGORY_COUNT);
//Decrease the mineral count for the category
mineralCounts[categoryIdx] = mineralCounts[categoryIdx] - 1;
//Decrease total mineral count
gemsLeft = gemsLeft - 1;
Gemstone memory _stone = Gemstone({
category : categoryIdx,
name : _name,
colour : _generateRandomHash(_name),
extractionTime : uint64(block.timestamp),
polishedTime : 0,
price : 0
});
uint256 newStoneId = gemstones.push(_stone) - 1;
ownerOreCount[msg.sender]--;
ownerGemCount[msg.sender]++;
gemIndexToOwner[newStoneId] = msg.sender;
return (categoryIdx, _stone.colour);
}
function polishRoughStone(uint256 _gemId) external payable {
uint gainedWei = msg.value;
require(gemIndexToOwner[_gemId] == msg.sender);
Gemstone storage gem = gemstones[_gemId];
require(gem.polishedTime == 0);
require(gainedWei >= _getPolishingPrice(gem.category));
gem.polishedTime = uint64(block.timestamp);
}
}
// The Ownership contract makes sure the requirements of the NFT are met
contract MineralOwnership is MineralFactory, ERC721 {
string public constant name = "CryptoMinerals";
string public constant symbol = "GEM";
function _owns(address _claimant, uint256 _gemId) internal view returns (bool) {
return gemIndexToOwner[_gemId] == _claimant;
}
// Assigns ownership of a specific gem to an address.
function _transfer(address _from, address _to, uint256 _gemId) internal {
require(_from != address(0));
require(_to != address(0));
ownerGemCount[_from]--;
ownerGemCount[_to]++;
gemIndexToOwner[_gemId] = _to;
Transfer(_from, _to, _gemId);
}
function _approvedFor(address _claimant, uint256 _gemId) internal view returns (bool) {
return gemIndexToApproved[_gemId] == _claimant;
}
function _approve(uint256 _gemId, address _approved) internal {
gemIndexToApproved[_gemId] = _approved;
}
// Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownerGemCount[_owner];
}
// Required for ERC-721 compliance.
function transfer(address _to, uint256 _gemId) external whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _gemId));
_transfer(msg.sender, _to, _gemId);
}
// Required for ERC-721 compliance.
function approve(address _to, uint256 _gemId) external whenNotPaused {
require(_owns(msg.sender, _gemId));
_approve(_gemId, _to);
Approval(msg.sender, _to, _gemId);
}
// Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _gemId) external whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _gemId));
require(_owns(_from, _gemId));
_transfer(_from, _to, _gemId);
}
// Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return TOTAL_SUPPLY - gemsLeft;
}
// Required for ERC-721 compliance.
function ownerOf(uint256 _gemId) external view returns (address owner) {
owner = gemIndexToOwner[_gemId];
require(owner != address(0));
}
// Required for ERC-721 compliance.
function implementsERC721() public view returns (bool implementsERC721) {
return true;
}
function gemsOfOwner(address _owner) external view returns(uint256[] ownerGems) {
uint256 gemCount = balanceOf(_owner);
if (gemCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](gemCount);
uint256 totalGems = totalSupply();
uint256 resultIndex = 0;
uint256 gemId;
for (gemId = 0; gemId <= totalGems; gemId++) {
if (gemIndexToOwner[gemId] == _owner) {
result[resultIndex] = gemId;
resultIndex++;
}
}
return result;
}
}
}
// This contract introduces functionalities for the basic trading
contract MineralMarket is MineralOwnership {
function buyOre() external payable {
require(msg.sender != address(0));
require(msg.value >= orePrice);
require(oresLeft > 0);
uint8 amount;
if (isPresale) {
require(discounts > 0);
amount = 50;
discounts--;
} else {
amount = 1;
}
oresLeft -= amount;
ownerOreCount[msg.sender] += amount;
}
function buyGem(uint _gemId) external payable {
uint gainedWei = msg.value;
require(msg.sender != address(0));
require(_gemId < gemstones.length);
require(gemIndexToOwner[_gemId] == address(this));
Gemstone storage gem = gemstones[_gemId];
require(gainedWei >= gem.price);
_transfer(address(this), msg.sender, _gemId);
}
function mintGem(uint _categoryIdx, string _name, uint256 _colour, bool _polished, uint256 _price) onlyTeamMembers external {
require(gemsLeft > 0);
require(_categoryIdx < CATEGORY_COUNT);
//Decrease the mineral count for the category if not PROMO gem
if (_categoryIdx < CATEGORY_COUNT){
mineralCounts[_categoryIdx] = mineralCounts[_categoryIdx] - 1;
}
uint64 stamp = 0;
if (_polished) {
stamp = uint64(block.timestamp);
}
//Decrease counters
gemsLeft = gemsLeft - 1;
oresLeft--;
Gemstone memory _stone = Gemstone({
category : _categoryIdx,
name : _name,
colour : _colour,
extractionTime : uint64(block.timestamp),
polishedTime : stamp,
price : _price
});
uint256 newStoneId = gemstones.push(_stone) - 1;
ownerGemCount[address(this)]++;
gemIndexToOwner[newStoneId] = address(this);
}
function setPrice(uint256 _gemId, uint256 _price) onlyTeamMembers external {
require(_gemId < gemstones.length);
Gemstone storage gem = gemstones[_gemId];
gem.price = uint64(_price);
}
function setMyPrice(uint256 _gemId, uint256 _price) external {
require(_gemId < gemstones.length);
require(gemIndexToOwner[_gemId] == msg.sender);
Gemstone storage gem = gemstones[_gemId];
gem.price = uint64(_price);
}
function withdrawBalance() onlyTeamMembers external {
bool res = owner.send(address(this).balance);
}
}
|
Assigns ownership of a specific gem to an address.
|
function _transfer(address _from, address _to, uint256 _gemId) internal {
require(_from != address(0));
require(_to != address(0));
ownerGemCount[_from]--;
ownerGemCount[_to]++;
gemIndexToOwner[_gemId] = _to;
Transfer(_from, _to, _gemId);
}
| 396,407 |
pragma solidity 0.4.24;
contract ExecutionTarget {
uint256 public counter;
function execute() public {
counter += 1;
emit Executed(counter);
}
function setCounter(uint256 x) public {
counter = x;
}
event Executed(uint256 x);
}
pragma solidity 0.4.24;
import "@aragon/os/contracts/acl/ACL.sol";
import "@aragon/os/contracts/kernel/Kernel.sol";
import "@aragon/os/contracts/factory/DAOFactory.sol";
import "@aragon/os/contracts/factory/APMRegistryFactory.sol";
import "@aragon/os/contracts/factory/ENSFactory.sol";
import "@aragon/os/contracts/apm/APMRegistry.sol";
import "@aragon/os/contracts/apm/Repo.sol";
import "@aragon/os/contracts/ens/ENSSubdomainRegistrar.sol";
import "@aragon/os/contracts/lib/ens/ENS.sol";
import "@aragon/os/contracts/lib/ens/AbstractENS.sol";
import "@aragon/os/contracts/lib/ens/PublicResolver.sol";
import "@aragon/test-helpers/contracts/TokenMock.sol";
contract Imports {
// solium-disable-previous-line no-empty-blocks
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
import "../common/ConversionHelpers.sol";
import "../common/TimeHelpers.sol";
import "./ACLSyntaxSugar.sol";
import "./IACL.sol";
import "./IACLOracle.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
bool ok;
assembly {
// send all available gas; if the oracle eats up all the gas, we will eventually revert
// note that we are currently guaranteed to still have some gas after the call from
// EIP-150's 63/64 gas forward rule
ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./AppStorage.sol";
import "../acl/ACLSyntaxSugar.sol";
import "../common/Autopetrified.sol";
import "../common/ConversionHelpers.sol";
import "../common/ReentrancyGuard.sol";
import "../common/VaultRecoverable.sol";
import "../evmscript/EVMScriptRunner.sol";
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../common/UnstructuredStorage.sol";
import "../kernel/IKernel.sol";
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../acl/IACL.sol";
import "../common/IVaultRecoverable.sol";
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Petrifiable.sol";
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Initializable.sol";
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./TimeHelpers.sol";
import "./UnstructuredStorage.sol";
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./Uint256Helpers.sol";
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../common/UnstructuredStorage.sol";
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../lib/token/ERC20.sol";
import "./EtherTokenConstant.sol";
import "./IsContract.sol";
import "./IVaultRecoverable.sol";
import "./SafeERC20.sol";
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
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 approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
import "../lib/token/ERC20.sol";
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return totalSupply;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./IEVMScriptExecutor.sol";
import "./IEVMScriptRegistry.sol";
import "../apps/AppStorage.sol";
import "../kernel/KernelConstants.sol";
import "../common/Initializable.sol";
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "./IEVMScriptExecutor.sol";
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
pragma solidity 0.4.24;
import "./IKernel.sol";
import "./KernelConstants.sol";
import "./KernelStorage.sol";
import "../acl/IACL.sol";
import "../acl/ACLSyntaxSugar.sol";
import "../common/ConversionHelpers.sol";
import "../common/IsContract.sol";
import "../common/Petrifiable.sol";
import "../common/VaultRecoverable.sol";
import "../factory/AppProxyFactory.sol";
import "../lib/misc/ERCProxy.sol";
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
pragma solidity 0.4.24;
import "../apps/AppProxyUpgradeable.sol";
import "../apps/AppProxyPinned.sol";
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
pragma solidity 0.4.24;
import "./AppProxyBase.sol";
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
pragma solidity 0.4.24;
import "./AppStorage.sol";
import "../common/DepositableDelegateProxy.sol";
import "../kernel/KernelConstants.sol";
import "../kernel/IKernel.sol";
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
pragma solidity 0.4.24;
import "./DelegateProxy.sol";
import "./DepositableStorage.sol";
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
uint256 forwardGasThreshold = FWD_GAS_LIMIT;
bytes32 isDepositablePosition = DEPOSITABLE_POSITION;
// Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity:
// https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20
assembly {
// Continue only if the gas left is lower than the threshold for forwarding to the implementation code,
// otherwise continue outside of the assembly block.
if lt(gas, forwardGasThreshold) {
// Only accept the deposit and emit an event if all of the following are true:
// the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0
if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) {
// Equivalent Solidity code for emitting the event:
// emit ProxyDeposit(msg.sender, msg.value);
let logData := mload(0x40) // free memory pointer
mstore(logData, caller) // add 'msg.sender' to the log data (first event param)
mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param)
// Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1
log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1)
stop() // Stop. Exits execution context
}
// If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender)
revert(0, 0)
}
}
address target = implementation();
delegatedFwd(target, msg.data);
}
}
pragma solidity 0.4.24;
import "../common/IsContract.sol";
import "../lib/misc/ERCProxy.sol";
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
pragma solidity 0.4.24;
import "./UnstructuredStorage.sol";
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
pragma solidity 0.4.24;
import "../common/UnstructuredStorage.sol";
import "../common/IsContract.sol";
import "./AppProxyBase.sol";
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
pragma solidity 0.4.24;
import "../kernel/IKernel.sol";
import "../kernel/Kernel.sol";
import "../kernel/KernelProxy.sol";
import "../acl/IACL.sol";
import "../acl/ACL.sol";
import "./EVMScriptRegistryFactory.sol";
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
pragma solidity 0.4.24;
import "./IKernel.sol";
import "./KernelConstants.sol";
import "./KernelStorage.sol";
import "../common/DepositableDelegateProxy.sol";
import "../common/IsContract.sol";
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
pragma solidity 0.4.24;
import "../evmscript/IEVMScriptExecutor.sol";
import "../evmscript/EVMScriptRegistry.sol";
import "../evmscript/executors/CallsScript.sol";
import "../kernel/Kernel.sol";
import "../acl/ACL.sol";
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
import "./ScriptHelpers.sol";
import "./IEVMScriptExecutor.sol";
import "./IEVMScriptRegistry.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
import "../ScriptHelpers.sol";
import "./BaseEVMScriptExecutor.sol";
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
import "../../common/Autopetrified.sol";
import "../IEVMScriptExecutor.sol";
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
pragma solidity 0.4.24;
import "../apm/APMRegistry.sol";
import "../apm/Repo.sol";
import "../ens/ENSSubdomainRegistrar.sol";
import "./DAOFactory.sol";
import "./ENSFactory.sol";
import "./AppProxyFactory.sol";
contract APMRegistryFactory is APMInternalAppNames {
DAOFactory public daoFactory;
APMRegistry public registryBase;
Repo public repoBase;
ENSSubdomainRegistrar public ensSubdomainRegistrarBase;
ENS public ens;
event DeployAPM(bytes32 indexed node, address apm);
/**
* @notice Create a new factory for deploying Aragon Package Managers (aragonPM)
* @dev Requires either a given ENS registrar or ENSFactory (used for generating a new ENS in test environments).
* @param _daoFactory Base factory for deploying DAOs
* @param _registryBase APMRegistry base contract location
* @param _repoBase Repo base contract location
* @param _ensSubBase ENSSubdomainRegistrar base contract location
* @param _ens ENS instance
* @param _ensFactory ENSFactory (used to generated a new ENS if no ENS is given)
*/
constructor(
DAOFactory _daoFactory,
APMRegistry _registryBase,
Repo _repoBase,
ENSSubdomainRegistrar _ensSubBase,
ENS _ens,
ENSFactory _ensFactory
) public // DAO initialized without evmscript run support
{
daoFactory = _daoFactory;
registryBase = _registryBase;
repoBase = _repoBase;
ensSubdomainRegistrarBase = _ensSubBase;
// Either the ENS address provided is used, if any.
// Or we use the ENSFactory to generate a test instance of ENS
// If not the ENS address nor factory address are provided, this will revert
ens = _ens != address(0) ? _ens : _ensFactory.newENS(this);
}
/**
* @notice Create a new Aragon Package Manager (aragonPM) DAO, holding the `_label` subdomain from parent `_tld` and controlled by `_root`
* @param _tld The parent node of the controlled subdomain
* @param _label The subdomain label
* @param _root Manager for the new aragonPM DAO
* @return The new aragonPM's APMRegistry app
*/
function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) {
bytes32 node = keccak256(abi.encodePacked(_tld, _label));
// Assume it is the test ENS
if (ens.owner(node) != address(this)) {
// If we weren't in test ens and factory doesn't have ownership, will fail
require(ens.owner(_tld) == address(this));
ens.setSubnodeOwner(_tld, _label, this);
}
Kernel dao = daoFactory.newDAO(this);
ACL acl = ACL(dao.acl());
acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this);
// Deploy app proxies
bytes memory noInit = new bytes(0);
ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar(
dao.newAppInstance(
keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(ENS_SUB_APP_NAME)))),
ensSubdomainRegistrarBase,
noInit,
false
)
);
APMRegistry apm = APMRegistry(
dao.newAppInstance(
keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(APM_APP_NAME)))),
registryBase,
noInit,
false
)
);
// APMRegistry controls Repos
bytes32 repoAppId = keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(REPO_APP_NAME))));
dao.setApp(dao.APP_BASES_NAMESPACE(), repoAppId, repoBase);
emit DeployAPM(node, apm);
// Grant permissions needed for APM on ENSSubdomainRegistrar
acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root);
acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root);
// allow apm to create permissions for Repos in Kernel
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
acl.grantPermission(apm, acl, permRole);
// Initialize
ens.setOwner(node, ensSub);
ensSub.initialize(ens, node);
apm.initialize(ensSub);
uint16[3] memory firstVersion;
firstVersion[0] = 1;
acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this);
apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm"));
apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub"));
apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo"));
configureAPMPermissions(acl, apm, _root);
// Permission transition to _root
acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE());
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
return apm;
}
function b(string memory x) internal pure returns (bytes memory y) {
y = bytes(x);
}
// Factory can be subclassed and permissions changed
function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal {
_acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE());
_acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE());
}
}
pragma solidity 0.4.24;
import "../lib/ens/AbstractENS.sol";
import "../ens/ENSSubdomainRegistrar.sol";
import "../factory/AppProxyFactory.sol";
import "../apps/AragonApp.sol";
import "../acl/ACL.sol";
import "./Repo.sol";
contract APMInternalAppNames {
string internal constant APM_APP_NAME = "apm-registry";
string internal constant REPO_APP_NAME = "apm-repo";
string internal constant ENS_SUB_APP_NAME = "apm-enssub";
}
contract APMRegistry is AragonApp, AppProxyFactory, APMInternalAppNames {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_REPO_ROLE = keccak256("CREATE_REPO_ROLE");
*/
bytes32 public constant CREATE_REPO_ROLE = 0x2a9494d64846c9fdbf0158785aa330d8bc9caf45af27fa0e8898eb4d55adcea6;
string private constant ERROR_INIT_PERMISSIONS = "APMREG_INIT_PERMISSIONS";
string private constant ERROR_EMPTY_NAME = "APMREG_EMPTY_NAME";
AbstractENS public ens;
ENSSubdomainRegistrar public registrar;
event NewRepo(bytes32 id, string name, address repo);
/**
* NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar
* @dev Initialize can only be called once. It saves the block number in which it was initialized
* @notice Initialize this APMRegistry instance and set `_registrar` as the ENS subdomain registrar
* @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership
*/
function initialize(ENSSubdomainRegistrar _registrar) public onlyInit {
initialized();
registrar = _registrar;
ens = registrar.ens();
registrar.pointRootNode(this);
// Check APM has all permissions it needss
ACL acl = ACL(kernel().acl());
require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS);
require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS);
}
/**
* @notice Create new repo in registry with `_name`
* @param _name Repo name, must be ununsed
* @param _dev Address that will be given permission to create versions
*/
function newRepo(string _name, address _dev) public auth(CREATE_REPO_ROLE) returns (Repo) {
return _newRepo(_name, _dev);
}
/**
* @notice Create new repo in registry with `_name` and publish a first version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _name Repo name
* @param _dev Address that will be given permission to create versions
* @param _initialSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newRepoWithVersion(
string _name,
address _dev,
uint16[3] _initialSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_REPO_ROLE) returns (Repo)
{
Repo repo = _newRepo(_name, this); // need to have permissions to create version
repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI);
// Give permissions to _dev
ACL acl = ACL(kernel().acl());
acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE());
acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE());
acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE());
return repo;
}
function _newRepo(string _name, address _dev) internal returns (Repo) {
require(bytes(_name).length > 0, ERROR_EMPTY_NAME);
Repo repo = newClonedRepo();
ACL(kernel().acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev);
// Creates [name] subdomain in the rootNode and sets registry as resolver
// This will fail if repo name already exists
bytes32 node = registrar.createNameAndPoint(keccak256(abi.encodePacked(_name)), repo);
emit NewRepo(node, _name, repo);
return repo;
}
function newClonedRepo() internal returns (Repo repo) {
repo = Repo(newAppProxy(kernel(), repoAppId()));
repo.initialize();
}
function repoAppId() internal view returns (bytes32) {
return keccak256(abi.encodePacked(registrar.rootNode(), keccak256(abi.encodePacked(REPO_APP_NAME))));
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
pragma solidity 0.4.24;
import "../lib/ens/AbstractENS.sol";
import "../lib/ens/PublicResolver.sol";
import "./ENSConstants.sol";
import "../apps/AragonApp.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract ENSSubdomainRegistrar is AragonApp, ENSConstants {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_NAME_ROLE = keccak256("CREATE_NAME_ROLE");
bytes32 public constant DELETE_NAME_ROLE = keccak256("DELETE_NAME_ROLE");
bytes32 public constant POINT_ROOTNODE_ROLE = keccak256("POINT_ROOTNODE_ROLE");
*/
bytes32 public constant CREATE_NAME_ROLE = 0xf86bc2abe0919ab91ef714b2bec7c148d94f61fdb069b91a6cfe9ecdee1799ba;
bytes32 public constant DELETE_NAME_ROLE = 0x03d74c8724218ad4a99859bcb2d846d39999449fd18013dd8d69096627e68622;
bytes32 public constant POINT_ROOTNODE_ROLE = 0x9ecd0e7bddb2e241c41b595a436c4ea4fd33c9fa0caa8056acf084fc3aa3bfbe;
string private constant ERROR_NO_NODE_OWNERSHIP = "ENSSUB_NO_NODE_OWNERSHIP";
string private constant ERROR_NAME_EXISTS = "ENSSUB_NAME_EXISTS";
string private constant ERROR_NAME_DOESNT_EXIST = "ENSSUB_DOESNT_EXIST";
AbstractENS public ens;
bytes32 public rootNode;
event NewName(bytes32 indexed node, bytes32 indexed label);
event DeleteName(bytes32 indexed node, bytes32 indexed label);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized. This contract must be the owner of the `_rootNode` node so that it can create subdomains.
* @notice Initialize this ENSSubdomainRegistrar instance with `_ens` as the root ENS registry and `_rootNode` as the node to allocate subdomains under
* @param _ens Address of ENS registry
* @param _rootNode Node to allocate subdomains under
*/
function initialize(AbstractENS _ens, bytes32 _rootNode) public onlyInit {
initialized();
// We need ownership to create subnodes
require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP);
ens = _ens;
rootNode = _rootNode;
}
/**
* @notice Create a new ENS subdomain record for `_label` and assign ownership to `_owner`
* @param _label Label of new subdomain
* @param _owner Owner of new subdomain
* @return node Hash of created node
*/
function createName(bytes32 _label, address _owner) external auth(CREATE_NAME_ROLE) returns (bytes32 node) {
return _createName(_label, _owner);
}
/**
* @notice Create a new ENS subdomain record for `_label` that resolves to `_target` and is owned by this ENSSubdomainRegistrar
* @param _label Label of new subdomain
* @param _target Ethereum address this new subdomain label will point to
* @return node Hash of created node
*/
function createNameAndPoint(bytes32 _label, address _target) external auth(CREATE_NAME_ROLE) returns (bytes32 node) {
node = _createName(_label, this);
_pointToResolverAndResolve(node, _target);
}
/**
* @notice Deregister ENS subdomain record for `_label`
* @param _label Label of subdomain to deregister
*/
function deleteName(bytes32 _label) external auth(DELETE_NAME_ROLE) {
bytes32 node = getNodeForLabel(_label);
address currentOwner = ens.owner(node);
require(currentOwner != address(0), ERROR_NAME_DOESNT_EXIST); // fail if deleting unset name
if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver
ens.setSubnodeOwner(rootNode, _label, this);
}
ens.setResolver(node, address(0)); // remove resolver so it ends resolving
ens.setOwner(node, address(0));
emit DeleteName(node, _label);
}
/**
* @notice Resolve this ENSSubdomainRegistrar's root node to `_target`
* @param _target Ethereum address root node will point to
*/
function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) {
_pointToResolverAndResolve(rootNode, _target);
}
function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) {
node = getNodeForLabel(_label);
require(ens.owner(node) == address(0), ERROR_NAME_EXISTS); // avoid name reset
ens.setSubnodeOwner(rootNode, _label, _owner);
emit NewName(node, _label);
return node;
}
function _pointToResolverAndResolve(bytes32 _node, address _target) internal {
address publicResolver = getAddr(PUBLIC_RESOLVER_NODE);
ens.setResolver(_node, publicResolver);
PublicResolver(publicResolver).setAddr(_node, _target);
}
function getAddr(bytes32 node) internal view returns (address) {
address resolver = ens.resolver(node);
return PublicResolver(resolver).addr(node);
}
function getNodeForLabel(bytes32 _label) internal view returns (bytes32) {
return keccak256(abi.encodePacked(rootNode, _label));
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
import "./AbstractENS.sol";
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ENSConstants {
/* Hardcoded constants to save gas
bytes32 internal constant ENS_ROOT = bytes32(0);
bytes32 internal constant ETH_TLD_LABEL = keccak256("eth");
bytes32 internal constant ETH_TLD_NODE = keccak256(abi.encodePacked(ENS_ROOT, ETH_TLD_LABEL));
bytes32 internal constant PUBLIC_RESOLVER_LABEL = keccak256("resolver");
bytes32 internal constant PUBLIC_RESOLVER_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL));
*/
bytes32 internal constant ENS_ROOT = bytes32(0);
bytes32 internal constant ETH_TLD_LABEL = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0;
bytes32 internal constant ETH_TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae;
bytes32 internal constant PUBLIC_RESOLVER_LABEL = 0x329539a1d23af1810c48a07fe7fc66a3b34fbc8b37e9b3cdb97bb88ceab7e4bf;
bytes32 internal constant PUBLIC_RESOLVER_NODE = 0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5;
}
pragma solidity 0.4.24;
import "../apps/AragonApp.sol";
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
pragma solidity 0.4.24;
import "../lib/ens/ENS.sol";
import "../lib/ens/PublicResolver.sol";
import "../ens/ENSConstants.sol";
// WARNING: This is an incredibly trustful ENS deployment, do NOT use in production!
// This contract is NOT meant to be deployed to a live network.
// Its only purpose is to easily create ENS instances for testing aragonPM.
contract ENSFactory is ENSConstants {
event DeployENS(address ens);
/**
* @notice Create a new ENS and set `_owner` as the owner of the top level domain.
* @param _owner Owner of .eth
* @return ENS
*/
function newENS(address _owner) public returns (ENS) {
ENS ens = new ENS();
// Setup .eth TLD
ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this);
// Setup public resolver
PublicResolver resolver = new PublicResolver(ens);
ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this);
ens.setResolver(PUBLIC_RESOLVER_NODE, resolver);
resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver);
ens.setOwner(ETH_TLD_NODE, _owner);
ens.setOwner(ENS_ROOT, _owner);
emit DeployENS(ens);
return ens;
}
}
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
import "./AbstractENS.sol";
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) public {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// Modified from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/StandardToken.sol
pragma solidity 0.4.24;
import "@aragon/os/contracts/lib/math/SafeMath.sol";
contract TokenMock {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
uint256 private totalSupply_;
bool private allowTransfer_;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
// Allow us to set the inital balance for an account on construction
constructor(address initialAccount, uint256 initialBalance) public {
balances[initialAccount] = initialBalance;
totalSupply_ = initialBalance;
allowTransfer_ = true;
}
function totalSupply() public view returns (uint256) { return totalSupply_; }
/**
* @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];
}
/**
* @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 Set whether the token is transferable or not
* @param _allowTransfer Should token be transferable
*/
function setAllowTransfer(bool _allowTransfer) public {
allowTransfer_ = _allowTransfer;
}
/**
* @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(allowTransfer_);
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _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) {
// Assume we want to protect for the race condition
require(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(allowTransfer_);
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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;
}
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @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, ERROR_MUL_OVERFLOW);
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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW);
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, ERROR_ADD_OVERFLOW);
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, ERROR_DIV_ZERO);
return a % b;
}
}
pragma solidity ^0.4.24;
import "@aragon/os/contracts/lib/math/SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal supply;
string public name;
string public symbol;
uint8 public decimals;
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply
) public {
supply = _totalSupply; // Update total supply
name = _name; // Set the id for reference
symbol = _symbol;
decimals = _decimals;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply); // Transfer event indicating token creation
}
/**
* @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 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(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _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 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(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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 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, uint256 _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, uint256 _subtractedValue) public returns (bool) {
uint256 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;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return supply;
}
/**
* @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];
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity 0.4.24;
import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol";
// NOTE: used because truffle does not support function overloading
contract VotingMock is DandelionVoting {
function newVoteExt(
bytes _executionScript,
string _metadata,
bool _castVote
) external returns (uint256) {
return _newVote(_executionScript, _metadata, _castVote);
}
}
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/IForwarder.sol";
import "@aragon/os/contracts/acl/IACLOracle.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/math/SafeMath64.sol";
import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol";
contract DandelionVoting is IForwarder, IACLOracle, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
bytes32 public constant MODIFY_BUFFER_BLOCKS_ROLE = keccak256("MODIFY_BUFFER_BLOCKS_ROLE");
bytes32 public constant MODIFY_EXECUTION_DELAY_ROLE = keccak256("MODIFY_EXECUTION_DELAY_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint8 private constant EXECUTION_PERIOD_FALLBACK_DIVISOR = 2;
string private constant ERROR_VOTE_ID_ZERO = "DANDELION_VOTING_VOTE_ID_ZERO";
string private constant ERROR_NO_VOTE = "DANDELION_VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "DANDELION_VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "DANDELION_VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "DANDELION_VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "DANDELION_VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "DANDELION_VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "DANDELION_VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "DANDELION_VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "DANDELION_VOTING_CAN_NOT_FORWARD";
string private constant ERROR_ORACLE_SENDER_MISSING = "DANDELION_VOTING_ORACLE_SENDER_MISSING";
string private constant ERROR_ORACLE_SENDER_TOO_BIG = "DANDELION_VOTING_ORACLE_SENDER_TOO_BIG";
string private constant ERROR_ORACLE_SENDER_ZERO = "DANDELION_VOTING_ORACLE_SENDER_ZERO";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startBlock;
uint64 executionBlock;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public durationBlocks;
uint64 public bufferBlocks;
uint64 public executionDelayBlocks;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
mapping (address => uint256) public latestYeaVoteId;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
event ChangeBufferBlocks(uint64 bufferBlocks);
event ChangeExecutionDelayBlocks(uint64 executionDelayBlocks);
modifier voteExists(uint256 _voteId) {
require(_voteId != 0, ERROR_VOTE_ID_ZERO);
require(_voteId <= votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, a voting duration of `_voteDurationBlocks` blocks, and a vote buffer of `_voteBufferBlocks` blocks
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _durationBlocks Blocks that a vote will be open for token holders to vote
* @param _bufferBlocks Minimum number of blocks between the start block of each vote
* @param _executionDelayBlocks Minimum number of blocks between the end of a vote and when it can be executed
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _durationBlocks,
uint64 _bufferBlocks,
uint64 _executionDelayBlocks
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
durationBlocks = _durationBlocks;
bufferBlocks = _bufferBlocks;
executionDelayBlocks = _executionDelayBlocks;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Change vote buffer to `_voteBufferBlocks` blocks
* @param _bufferBlocks New vote buffer defined in blocks
*/
function changeBufferBlocks(uint64 _bufferBlocks) external auth(MODIFY_BUFFER_BLOCKS_ROLE) {
bufferBlocks = _bufferBlocks;
emit ChangeBufferBlocks(_bufferBlocks);
}
/**
* @notice Change execution delay to `_executionDelayBlocks` blocks
* @param _executionDelayBlocks New vote execution delay defined in blocks
*/
function changeExecutionDelayBlocks(uint64 _executionDelayBlocks) external auth(MODIFY_EXECUTION_DELAY_ROLE) {
executionDelayBlocks = _executionDelayBlocks;
emit ChangeExecutionDelayBlocks(_executionDelayBlocks);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
*/
function vote(uint256 _voteId, bool _supports) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
// Forwarding fns
/**
* @notice Returns whether the Voting app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true);
}
/**
* @notice Returns whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can create votes, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// ACL Oracle fns
/**
* @notice Returns whether the sender has voted on the most recent open vote or closed unexecuted vote.
* @dev IACLOracle interface conformance. The ACLOracle permissioned function should specify the sender
* with 'authP(SOME_ACL_ROLE, arr(sender))', where sender is typically set to 'msg.sender'.
* @param _how Array passed by Kernel when using 'authP()'. First item should be the address to check can perform.
* return False if the sender has voted on the most recent open vote or closed unexecuted vote, true if they haven't.
*/
function canPerform(address, address, bytes32, uint256[] _how) external view returns (bool) {
if (votesLength == 0) {
return true;
}
require(_how.length > 0, ERROR_ORACLE_SENDER_MISSING);
require(_how[0] < 2**160, ERROR_ORACLE_SENDER_TOO_BIG);
require(_how[0] != 0, ERROR_ORACLE_SENDER_ZERO);
address sender = address(_how[0]);
uint256 senderLatestYeaVoteId = latestYeaVoteId[sender];
Vote storage senderLatestYeaVote_ = votes[senderLatestYeaVoteId];
uint64 blockNumber = getBlockNumber64();
bool senderLatestYeaVoteFailed = !_votePassed(senderLatestYeaVote_);
bool senderLatestYeaVoteExecutionBlockPassed = blockNumber >= senderLatestYeaVote_.executionBlock;
uint64 fallbackPeriodLength = bufferBlocks / EXECUTION_PERIOD_FALLBACK_DIVISOR;
bool senderLatestYeaVoteFallbackPeriodPassed = blockNumber > senderLatestYeaVote_.executionBlock.add(fallbackPeriodLength);
return senderLatestYeaVoteFailed && senderLatestYeaVoteExecutionBlockPassed || senderLatestYeaVote_.executed || senderLatestYeaVoteFallbackPeriodPassed;
}
// Getter fns
/**
* @notice Tells whether a vote #`_voteId` can be executed or not
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @return True if the given vote can be executed, false otherwise
*/
function canExecute(uint256 _voteId) public view returns (bool) {
return _canExecute(_voteId);
}
/**
* @notice Tells whether `_sender` can participate in the vote #`_voteId` or not
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @return True if the given voter can participate a certain vote, false otherwise
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
/**
* @dev Return all information for a vote by its ID
* @param _voteId Vote identifier
* @return Vote open status
* @return Vote executed status
* @return Vote start block
* @return Vote snapshot block
* @return Vote support required
* @return Vote minimum acceptance quorum
* @return Vote yeas amount
* @return Vote nays amount
* @return Vote power
* @return Vote script
*/
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startBlock,
uint64 executionBlock,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 votingPower,
uint256 yea,
uint256 nay,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startBlock = vote_.startBlock;
executionBlock = vote_.executionBlock;
snapshotBlock = vote_.snapshotBlock;
votingPower = token.totalSupplyAt(vote_.snapshotBlock);
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
script = vote_.executionScript;
}
/**
* @dev Return the state of a voter for a given vote by its ID
* @param _voteId Vote identifier
* @return VoterState of the requested voter for a certain vote
*/
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
/**
* @dev Internal function to create a new vote
* @return voteId id for newly created vote
*/
function _newVote(bytes _executionScript, string _metadata, bool _castVote) internal returns (uint256 voteId) {
voteId = ++votesLength; // Increment votesLength before assigning to votedId. The first voteId is 1.
uint64 previousVoteStartBlock = votes[voteId - 1].startBlock;
uint64 earliestStartBlock = previousVoteStartBlock == 0 ? 0 : previousVoteStartBlock.add(bufferBlocks);
uint64 startBlock = earliestStartBlock < getBlockNumber64() ? getBlockNumber64() : earliestStartBlock;
uint64 executionBlock = startBlock.add(durationBlocks).add(executionDelayBlocks);
Vote storage vote_ = votes[voteId];
vote_.startBlock = startBlock;
vote_.executionBlock = executionBlock;
vote_.snapshotBlock = startBlock - 1; // avoid double voting in this very block
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender);
}
}
/**
* @dev Internal function to cast a vote. It assumes the queried vote exists.
*/
function _vote(uint256 _voteId, bool _supports, address _voter) internal {
Vote storage vote_ = votes[_voteId];
uint256 voterStake = _voterStake(vote_, _voter);
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
if (latestYeaVoteId[_voter] < _voteId) {
latestYeaVoteId[_voter] = _voteId;
}
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
}
/**
* @dev Internal function to check if a vote can be executed. It assumes the queried vote exists.
* @return True if the given vote can be executed, false otherwise
*/
function _canExecute(uint256 _voteId) internal view voteExists(_voteId) returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// This will always be later than the end of the previous vote
if (getBlockNumber64() < vote_.executionBlock) {
return false;
}
return _votePassed(vote_);
}
/**
* @dev Internal function to check if a vote has passed. It assumes the vote period has passed.
* @return True if the given vote has passed, false otherwise.
*/
function _votePassed(Vote storage vote_) internal view returns (bool) {
uint256 totalVotes = vote_.yea.add(vote_.nay);
uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock);
bool hasSupportRequired = _isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct);
bool hasMinQuorum = _isValuePct(vote_.yea, votingPowerAtSnapshot, vote_.minAcceptQuorumPct);
return hasSupportRequired && hasMinQuorum;
}
/**
* @dev Internal function to check if a voter can participate on a vote. It assumes the queried vote exists.
* @return True if the given voter can participate a certain vote, false otherwise
*/
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
uint256 voterStake = _voterStake(vote_, _voter);
bool hasNotVoted = vote_.voters[_voter] == VoterState.Absent;
return _isVoteOpen(vote_) && voterStake > 0 && hasNotVoted;
}
/**
* @dev Internal function to determine a voters stake which is the minimum of snapshot balance and current balance.
* @return Voters current stake.
*/
function _voterStake(Vote storage vote_, address _voter) internal view returns (uint256) {
uint256 balanceAtSnapshot = token.balanceOfAt(_voter, vote_.snapshotBlock);
uint256 currentBalance = token.balanceOf(_voter);
return balanceAtSnapshot < currentBalance ? balanceAtSnapshot : currentBalance;
}
/**
* @dev Internal function to check if a vote is still open
* @return True if the given vote is open, false otherwise
*/
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock);
uint64 blockNumber = getBlockNumber64();
return votingPowerAtSnapshot > 0 && blockNumber >= vote_.startBlock && blockNumber < vote_.startBlock.add(durationBlocks);
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
import "./ITokenController.sol";
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
/// @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) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @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) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @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) external returns(bool);
}
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol";
import "@aragon/apps-vault/contracts/Vault.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/math/SafeMath64.sol";
import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol";
contract VotingRewards is AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CHANGE_EPOCH_DURATION_ROLE = keccak256("CHANGE_EPOCH_DURATION_ROLE");
bytes32 public constant CHANGE_LOCK_TIME_ROLE = keccak256("CHANGE_LOCK_TIME_ROLE");
bytes32 public constant CHANGE_MISSING_VOTES_THRESHOLD_ROLE = keccak256("CHANGE_MISSING_VOTES_THRESHOLD_ROLE");
bytes32 public constant OPEN_REWARDS_DISTRIBUTION_ROLE = keccak256("OPEN_REWARDS_DISTRIBUTION_ROLE");
bytes32 public constant CLOSE_REWARDS_DISTRIBUTION_ROLE = keccak256("CLOSE_REWARDS_DISTRIBUTION_ROLE");
bytes32 public constant DISTRIBUTE_REWARDS_ROLE = keccak256("DISTRIBUTE_REWARDS_ROLE");
bytes32 public constant CHANGE_PERCENTAGE_REWARDS_ROLE = keccak256("CHANGE_PERCENTAGE_REWARDS_ROLE");
bytes32 public constant CHANGE_VAULT_ROLE = keccak256("CHANGE_VAULT_ROLE");
bytes32 public constant CHANGE_REWARDS_TOKEN_ROLE = keccak256("CHANGE_REWARDS_TOKEN_ROLE");
bytes32 public constant CHANGE_VOTING_ROLE = keccak256("CHANGE_VOTING_ROLE");
uint64 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_ADDRESS_NOT_CONTRACT = "VOTING_REWARDS_ADDRESS_NOT_CONTRACT";
string private constant ERROR_EPOCH = "VOTING_REWARDS_ERROR_EPOCH";
string private constant ERROR_PERCENTAGE_REWARDS = "VOTING_REWARDS_ERROR_PERCENTAGE_REWARDS";
// prettier-ignore
string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED";
// prettier-ignore
string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED";
string private constant ERROR_NO_REWARDS = "VOTING_REWARDS_NO_REWARDS";
struct Reward {
uint256 amount;
uint64 lockBlock;
uint64 lockTime;
}
Vault public baseVault;
Vault public rewardsVault;
DandelionVoting public dandelionVoting;
address public rewardsToken;
uint256 public percentageRewards;
uint256 public missingVotesThreshold;
uint64 public epochDuration;
uint64 public currentEpoch;
uint64 public startBlockNumberOfCurrentEpoch;
uint64 public lockTime;
uint64 public lastRewardsDistributionBlock;
uint64 private deployBlock;
bool public isDistributionOpen;
// NOTE: previousRewardsDistributionBlockNumber kept even if not used so as not to break the proxy contract storage after an upgrade
mapping(address => uint64) private previousRewardsDistributionBlockNumber;
mapping(address => Reward[]) public addressUnlockedRewards;
mapping(address => Reward[]) public addressWithdrawnRewards; // kept even if not used so as not to break the proxy contract storage after an upgrade
event BaseVaultChanged(address baseVault);
event RewardsVaultChanged(address rewardsVault);
event DandelionVotingChanged(address dandelionVoting);
event PercentageRewardsChanged(uint256 percentageRewards);
event RewardDistributed(address indexed beneficiary, uint256 indexed amount, uint64 lockTime);
event RewardCollected(address indexed beneficiary, uint256 amount, uint64 indexed lockBlock, uint64 lockTime);
event EpochDurationChanged(uint64 epochDuration);
event MissingVoteThresholdChanged(uint256 missingVotesThreshold);
event LockTimeChanged(uint64 lockTime);
event RewardsDistributionEpochOpened(uint64 startBlock, uint64 endBlock);
event RewardsDistributionEpochClosed(uint64 rewardDistributionBlock);
event RewardsTokenChanged(address rewardsToken);
/**
* @notice Initialize VotingRewards app contract
* @param _baseVault Vault address from which token are taken
* @param _rewardsVault Vault address to which token are put
* @param _rewardsToken Accepted token address
* @param _epochDuration number of blocks for which an epoch is opened
* @param _percentageRewards percentage of a reward expressed as a number between 10^16 and 10^18
* @param _lockTime number of blocks for which token will be locked after colleting reward
* @param _missingVotesThreshold number of missing votes allowed in an epoch
*/
function initialize(
address _baseVault,
address _rewardsVault,
address _dandelionVoting,
address _rewardsToken,
uint64 _epochDuration,
uint256 _percentageRewards,
uint64 _lockTime,
uint256 _missingVotesThreshold
) external onlyInit {
require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT);
require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT);
require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS);
baseVault = Vault(_baseVault);
rewardsVault = Vault(_rewardsVault);
dandelionVoting = DandelionVoting(_dandelionVoting);
rewardsToken = _rewardsToken;
epochDuration = _epochDuration;
percentageRewards = _percentageRewards;
missingVotesThreshold = _missingVotesThreshold;
lockTime = _lockTime;
deployBlock = getBlockNumber64();
lastRewardsDistributionBlock = getBlockNumber64();
currentEpoch = 0;
initialized();
}
/**
* @notice Open the distribution for the current epoch from _fromBlock
* @param _fromBlock block from which starting to look for rewards
*/
function openRewardsDistributionForEpoch(uint64 _fromBlock) external auth(OPEN_REWARDS_DISTRIBUTION_ROLE) {
require(!isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED);
require(_fromBlock > lastRewardsDistributionBlock, ERROR_EPOCH);
require(getBlockNumber64() - lastRewardsDistributionBlock > epochDuration, ERROR_EPOCH);
startBlockNumberOfCurrentEpoch = _fromBlock;
isDistributionOpen = true;
emit RewardsDistributionEpochOpened(_fromBlock, _fromBlock + epochDuration);
}
/**
* @notice close distribution for thee current epoch if it's opened and starts a new one
*/
function closeRewardsDistributionForCurrentEpoch() external auth(CLOSE_REWARDS_DISTRIBUTION_ROLE) {
require(isDistributionOpen == true, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
isDistributionOpen = false;
currentEpoch = currentEpoch.add(1);
lastRewardsDistributionBlock = getBlockNumber64();
emit RewardsDistributionEpochClosed(lastRewardsDistributionBlock);
}
/**
* @notice distribute rewards for a list of address. Tokens are locked for lockTime in rewardsVault
* @param _beneficiaries address that are looking for reward
* @dev this function should be called from outside each _epochDuration seconds
*/
function distributeRewardsToMany(address[] _beneficiaries, uint256[] _amount)
external
auth(DISTRIBUTE_REWARDS_ROLE)
returns (bool)
{
require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
uint256 totalRewardAmount = 0;
for (uint256 i = 0; i < _beneficiaries.length; i++) {
// NOTE: switching to a semi-trusted solution in order to spend less in gas
// _assignUnlockedReward(_beneficiaries[i], _amount[i]);
totalRewardAmount = totalRewardAmount.add(_amount[i]);
emit RewardDistributed(_beneficiaries[i], _amount[i], lockTime);
}
baseVault.transfer(rewardsToken, rewardsVault, totalRewardAmount);
return true;
}
/**
* @notice Distribute rewards to _beneficiary
* @param _beneficiary address to which the deposit will be transferred if successful
* @dev baseVault should have TRANSFER_ROLE permission
*/
function distributeRewardsTo(address _beneficiary, uint256 _amount)
external
auth(DISTRIBUTE_REWARDS_ROLE)
returns (bool)
{
require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED);
// NOTE: switching to a semi-trusted solution in order to spend less in gas
// _assignUnlockedReward(_beneficiary, _amount);
baseVault.transfer(rewardsToken, rewardsVault, _amount);
emit RewardDistributed(_beneficiary, _amount, lockTime);
return true;
}
/**
* @notice collect rewards for a list of address
* if lockTime is passed since when tokens have been distributed
* @param _beneficiaries addresses that should be fund with rewards
*/
function collectRewardsForMany(address[] _beneficiaries) external {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
collectRewardsFor(_beneficiaries[i]);
}
}
/**
* @notice Change minimum number of seconds to claim dandelionVoting rewards
* @param _epochDuration number of seconds minimum to claim access to dandelionVoting rewards
*/
function changeEpochDuration(uint64 _epochDuration) external auth(CHANGE_EPOCH_DURATION_ROLE) {
require(_epochDuration > 0, ERROR_EPOCH);
epochDuration = _epochDuration;
emit EpochDurationChanged(_epochDuration);
}
/**
* @notice Change minimum number of missing votes allowed
* @param _missingVotesThreshold number of seconds minimum to claim access to voting rewards
*/
function changeMissingVotesThreshold(uint256 _missingVotesThreshold)
external
auth(CHANGE_MISSING_VOTES_THRESHOLD_ROLE)
{
missingVotesThreshold = _missingVotesThreshold;
emit MissingVoteThresholdChanged(_missingVotesThreshold);
}
/**
* @notice Change minimum number of missing votes allowed
* @param _lockTime number of seconds for which tokens will be locked after distributing reward
*/
function changeLockTime(uint64 _lockTime) external auth(CHANGE_LOCK_TIME_ROLE) {
lockTime = _lockTime;
emit LockTimeChanged(_lockTime);
}
/**
* @notice Change Base Vault
* @param _baseVault new base vault address
*/
function changeBaseVaultContractAddress(address _baseVault) external auth(CHANGE_VAULT_ROLE) {
require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT);
baseVault = Vault(_baseVault);
emit BaseVaultChanged(_baseVault);
}
/**
* @notice Change Reward Vault
* @param _rewardsVault new reward vault address
*/
function changeRewardsVaultContractAddress(address _rewardsVault) external auth(CHANGE_VAULT_ROLE) {
require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT);
rewardsVault = Vault(_rewardsVault);
emit RewardsVaultChanged(_rewardsVault);
}
/**
* @notice Change Dandelion Voting contract address
* @param _dandelionVoting new dandelionVoting address
*/
function changeDandelionVotingContractAddress(address _dandelionVoting) external auth(CHANGE_VOTING_ROLE) {
require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT);
dandelionVoting = DandelionVoting(_dandelionVoting);
emit DandelionVotingChanged(_dandelionVoting);
}
/**
* @notice Change percentage rewards
* @param _percentageRewards new percentage
* @dev PCT_BASE is the maximun allowed percentage
*/
function changePercentageRewards(uint256 _percentageRewards) external auth(CHANGE_PERCENTAGE_REWARDS_ROLE) {
require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS);
percentageRewards = _percentageRewards;
emit PercentageRewardsChanged(percentageRewards);
}
/**
* @notice Change rewards token
* @param _rewardsToken new percentage
*/
function changeRewardsTokenContractAddress(address _rewardsToken) external auth(CHANGE_REWARDS_TOKEN_ROLE) {
require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT);
rewardsToken = _rewardsToken;
emit RewardsTokenChanged(rewardsToken);
}
/**
* @notice Returns all unlocked rewards given an address
* @param _beneficiary address of which we want to get all rewards
*/
function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
return rewards;
}
/**
* @notice Returns all withdrawan rewards given an address
* @param _beneficiary address of which we want to get all rewards
*/
function getWithdrawnRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressWithdrawnRewards[_beneficiary];
return rewards;
}
/**
* @notice collect rewards for an msg.sender
*/
function collectRewards() external {
collectRewardsFor(msg.sender);
}
/**
* @notice collect rewards for an address if lockTime is passed since when tokens have been distributed
* @param _beneficiary address that should be fund with rewards
* @dev rewardsVault should have TRANSFER_ROLE permission
*/
function collectRewardsFor(address _beneficiary) public returns (bool) {
uint64 currentBlockNumber = getBlockNumber64();
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
uint256 rewardsLength = rewards.length;
require(rewardsLength > 0, ERROR_NO_REWARDS);
uint256 collectedRewardsAmount = 0;
for (uint256 i = 0; i < rewardsLength; i++) {
Reward reward = rewards[i];
if (currentBlockNumber - reward.lockBlock > reward.lockTime && !_isRewardEmpty(reward)) {
collectedRewardsAmount = collectedRewardsAmount + reward.amount;
emit RewardCollected(_beneficiary, reward.amount, reward.lockBlock, reward.lockTime);
delete rewards[i];
}
}
rewardsVault.transfer(rewardsToken, _beneficiary, collectedRewardsAmount);
return true;
}
/**
* @notice Check if msg.sender is able to be rewarded, and in positive case,
* he will be funded with the corresponding earned amount of tokens
* @param _beneficiary address to which the deposit will be transferred if successful
*/
function _assignUnlockedReward(address _beneficiary, uint256 _amount) internal returns (bool) {
Reward[] storage unlockedRewards = addressUnlockedRewards[_beneficiary];
uint64 currentBlockNumber = getBlockNumber64();
// prettier-ignore
uint64 lastBlockDistributedReward = unlockedRewards.length == 0 ? deployBlock : unlockedRewards[unlockedRewards.length - 1].lockBlock;
// NOTE: avoid double collecting for the same epoch
require(currentBlockNumber.sub(lastBlockDistributedReward) > epochDuration, ERROR_EPOCH);
addressUnlockedRewards[_beneficiary].push(Reward(_amount, currentBlockNumber, lockTime));
return true;
}
/**
* @notice Check if a Reward is empty
* @param _reward reward
*/
function _isRewardEmpty(Reward memory _reward) internal pure returns (bool) {
return _reward.amount == 0 && _reward.lockBlock == 0 && _reward.lockTime == 0;
}
}
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/common/DepositableStorage.sol";
import "@aragon/os/contracts/common/EtherTokenConstant.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
|
Create a new vote about "`_metadata`" _executionScript EVM script to be executed on approval _metadata Vote metadata _castVote Whether to also cast newly created vote return voteId id for newly created vote/
|
function newVote(bytes _executionScript, string _metadata, bool _castVote)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote);
}
| 13,453,887 |
./full_match/80001/0xC432FfEDBd797c504eEF6178F8869aF69c0a93ea/sources/contracts/1_Storage.sol
|
Transfer the NFT handle handle emit TexugoBought(tokenId, msg.value, seller, _msgSender());
|
function buyTexugo(uint256 tokenId) payable public {
Offer memory offer = texugosOfferedForSale[tokenId];
require(tokenId < 20020, "Out of tokenId");
require(offer.isForSale, "No Sale");
require(offer.onlySellTo == address(0) || offer.onlySellTo == _msgSender(), "Unable to sell");
require(msg.value >= offer.minValue, "Insufficient amount");
require(ownerOf(tokenId) == offer.seller, "Not seller");
address seller = offer.seller;
_safeTransfer(seller, _msgSender(), tokenId, "");
pendingWithdrawals[seller] += msg.value * 95 / 100;
fundsDon = msg.value * 50 / 1000;
fundsDraw = msg.value * 50 / 1000;
require(success);
}
| 5,600,088 |
./full_match/1/0xD02A7208809821bC465BfBA4865D544cC48a93E8/sources/contracts/NFTStandard.sol
|
See {IERC721Metadata-tokenURI}./
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "NS10");
string memory baseURI = _baseURI(tokenId);
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
| 3,037,579 |
./full_match/80001/0x75400278D938725E7257Cd29b41eD7A9C9fe7c8B/sources/project:/contracts/RodoBridgeTitleNFT.sol
|
Check requirements before minting NFT Throws if `titleId` is already stored in `titleTokenIds` titleId the Chase title id of NFT to be minted
|
function _beforeMintNFT(string memory titleId) internal virtual {
require(titleTokenIds[titleId] == 0, 'Already minted NFT for this title');
}
| 875,479 |
./partial_match/4/0x3b91c5A82850734AfCa4417Ee7e8114b6fBeB680/sources/IlikeTests.sol
|
Can be made private and use distributeEverything()Get maggots from storage contract as wellHow much maggot does this contract have?Approve this address to spend Maggotemit RewardsDistributedHROTMAGGOTEvent(MAGGOTBalance, block.number);Transfer Maggot to ROT/MAGGOT pool as Lp rewardsSync ROT/MAGGOT pool
|
function distributeLPRewardsForMaggotRot() public {
getMaggotAmountFromROTSTorage();
uint256 MAGGOTBalance = ERC20(maggotAddress).balanceOf(address(this));
require(MAGGOTBalance!=0,"Maggot balance should be more than 0");
ERC20(maggotAddress).approve(address(this), MAGGOTBalance);
ERC20(maggotAddress).transfer(ROTMAGGOTpair, MAGGOTBalance);
syncUniswapPairMaggotRot();
}
| 8,673,136 |
pragma solidity 0.4.24;
/**
* @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) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract TokenInterface {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function getMaxTotalSupply() public view returns (uint256);
function mint(address _to, uint256 _amount) public returns (bool);
function transfer(address _to, uint256 _amount) public returns (bool);
function allowance(
address _who,
address _spender
)
public
view
returns (uint256);
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool);
}
contract MiningTokenInterface {
function multiMint(address _to, uint256 _amount) external;
function getTokenTime(uint256 _tokenId) external returns(uint256);
function mint(address _to, uint256 _id) external;
function ownerOf(uint256 _tokenId) public view returns (address);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 _balance);
function tokenByIndex(uint256 _index) public view returns (uint256);
function arrayOfTokensByAddress(address _holder)
public
view
returns(uint256[]);
function getTokensCount(address _owner) public returns(uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
}
contract Management {
using SafeMath for uint256;
uint256 public startPriceForHLPMT = 10000;
uint256 public maxHLPMTMarkup = 40000;
uint256 public stepForPrice = 1000;
uint256 public startTime;
uint256 public lastMiningTime;
// default value
uint256 public decimals = 18;
TokenInterface public token;
MiningTokenInterface public miningToken;
address public dao;
address public fund;
address public owner;
// num of mining times
uint256 public numOfMiningTimes;
mapping(address => uint256) public payments;
mapping(address => uint256) public paymentsTimestamps;
// mining time => mining reward
mapping(uint256 => uint256) internal miningReward;
// id mining token => getting reward last mining
mapping(uint256 => uint256) internal lastGettingReward;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyDao() {
require(msg.sender == dao);
_;
}
constructor(
address _token,
address _miningToken,
address _dao,
address _fund
)
public
{
require(_token != address(0));
require(_miningToken != address(0));
require(_dao != address(0));
require(_fund != address(0));
startTime = now;
lastMiningTime = startTime - (startTime % (1 days)) - 1 days;
owner = msg.sender;
token = TokenInterface(_token);
miningToken = MiningTokenInterface(_miningToken);
dao = _dao;
fund = _fund;
}
/**
* @dev Exchanges the HLT tokens to HLPMT tokens. Works up to 48 HLPMT
* tokens at one-time buying. Should call after approving HLT tokens to
* manager address.
*/
function buyHLPMT() external {
uint256 _currentTime = now;
uint256 _allowed = token.allowance(msg.sender, address(this));
uint256 _currentPrice = getPrice(_currentTime);
require(_allowed >= _currentPrice);
//remove the remainder
uint256 _hlpmtAmount = _allowed.div(_currentPrice);
_allowed = _hlpmtAmount.mul(_currentPrice);
require(token.transferFrom(msg.sender, fund, _allowed));
for (uint256 i = 0; i < _hlpmtAmount; i++) {
uint256 _id = miningToken.totalSupply();
miningToken.mint(msg.sender, _id);
lastGettingReward[_id] = numOfMiningTimes;
}
}
/**
* @dev Produces the mining process and sends reward to dao and fund.
*/
function mining() external {
uint256 _currentTime = now;
require(_currentTime > _getEndOfLastMiningDay());
uint256 _missedDays = (_currentTime - lastMiningTime) / (1 days);
updateLastMiningTime(_currentTime);
for (uint256 i = 0; i < _missedDays; i++) {
// 0.1% daily from remaining unmined tokens.
uint256 _dailyTokens = token.getMaxTotalSupply().sub(token.totalSupply()).div(1000);
uint256 _tokensToDao = _dailyTokens.mul(3).div(10); // 30 percent
token.mint(dao, _tokensToDao);
uint256 _tokensToFund = _dailyTokens.mul(3).div(10); // 30 percent
token.mint(fund, _tokensToFund);
uint256 _miningTokenSupply = miningToken.totalSupply();
uint256 _tokensToMiners = _dailyTokens.mul(4).div(10); // 40 percent
uint256 _tokensPerMiningToken = _tokensToMiners.div(_miningTokenSupply);
miningReward[++numOfMiningTimes] = _tokensPerMiningToken;
token.mint(address(this), _tokensToMiners);
}
}
/**
* @dev Sends the daily mining reward to HLPMT holder.
*/
function getReward(uint256[] tokensForReward) external {
uint256 _rewardAmount = 0;
for (uint256 i = 0; i < tokensForReward.length; i++) {
if (
msg.sender == miningToken.ownerOf(tokensForReward[i]) &&
numOfMiningTimes > getLastRewardTime(tokensForReward[i])
) {
_rewardAmount += _calculateReward(tokensForReward[i]);
setLastRewardTime(tokensForReward[i], numOfMiningTimes);
}
}
require(_rewardAmount > 0);
token.transfer(msg.sender, _rewardAmount);
}
function checkReward(uint256[] tokensForReward) external view returns (uint256) {
uint256 reward = 0;
for (uint256 i = 0; i < tokensForReward.length; i++) {
if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) {
reward += _calculateReward(tokensForReward[i]);
}
}
return reward;
}
/**
* @param _tokenId token id
* @return timestamp of token creation
*/
function getLastRewardTime(uint256 _tokenId) public view returns(uint256) {
return lastGettingReward[_tokenId];
}
/**
* @dev Sends the daily mining reward to HLPMT holder.
*/
function sendReward(uint256[] tokensForReward) public onlyOwner {
for (uint256 i = 0; i < tokensForReward.length; i++) {
if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) {
uint256 reward = _calculateReward(tokensForReward[i]);
setLastRewardTime(tokensForReward[i], numOfMiningTimes);
token.transfer(miningToken.ownerOf(tokensForReward[i]), reward);
}
}
}
/**
* @dev Returns the HLPMT token amount of holder.
*/
function miningTokensOf(address holder) public view returns (uint256[]) {
return miningToken.arrayOfTokensByAddress(holder);
}
/**
* @dev Sets the DAO address
* @param _dao DAO address.
*/
function setDao(address _dao) public onlyOwner {
require(_dao != address(0));
dao = _dao;
}
/**
* @dev Sets the fund address
* @param _fund Fund address.
*/
function setFund(address _fund) public onlyOwner {
require(_fund != address(0));
fund = _fund;
}
/**
* @dev Sets the token address
* @param _token Token address.
*/
function setToken(address _token) public onlyOwner {
require(_token != address(0));
token = TokenInterface(_token);
}
/**
* @dev Sets the mining token address
* @param _miningToken Mining token address.
*/
function setMiningToken(address _miningToken) public onlyOwner {
require(_miningToken != address(0));
miningToken = MiningTokenInterface(_miningToken);
}
/**
* @return uint256 the current HLPMT token price in HLT (without decimals).
*/
function getPrice(uint256 _timestamp) public view returns(uint256) {
uint256 _raising = _timestamp.sub(startTime).div(30 days);
_raising = _raising.mul(stepForPrice);
if (_raising > maxHLPMTMarkup) _raising = maxHLPMTMarkup;
return (startPriceForHLPMT + _raising) * 10 ** 18;
}
/**
* @param _numOfMiningTime is time
* @return getting token reward
*/
function getMiningReward(uint256 _numOfMiningTime) public view returns (uint256) {
return miningReward[_numOfMiningTime];
}
/**
* @dev Returns the calculated reward amount.
*/
function _calculateReward(uint256 tokenID)
internal
view
returns (uint256 reward)
{
for (uint256 i = getLastRewardTime(tokenID) + 1; i <= numOfMiningTimes; i++) {
reward += miningReward[i];
}
return reward;
}
/**
* @dev set last getting token reward time
*/
function setLastRewardTime(uint256 _tokenId, uint256 _num) internal {
lastGettingReward[_tokenId] = _num;
}
/**
* @dev set last getting token reward time
*/
function updateLastMiningTime(uint256 _currentTime) internal {
lastMiningTime = _currentTime - _currentTime % (1 days);
}
/**
* @return uint256 the unix timestamp of the end of the last mining day.
*/
function _getEndOfLastMiningDay() internal view returns(uint256) {
return lastMiningTime + 1 days;
}
/**
* @dev Withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
uint256 timestamp = paymentsTimestamps[payee];
require(payment != 0);
require(now >= timestamp);
payments[payee] = 0;
require(token.transfer(msg.sender, payment));
}
/**
* @dev Called by the payer to store the sent _amount as credit to be pulled.
* @param _dest The destination address of the funds.
* @param _amount The amount to transfer.
*/
function asyncSend(address _dest, uint256 _amount, uint256 _timestamp) external onlyDao {
payments[_dest] = payments[_dest].add(_amount);
paymentsTimestamps[_dest] = _timestamp;
require(token.transferFrom(dao, address(this), _amount));
}
}
|
_numOfMiningTime is time return getting token reward/
|
function getMiningReward(uint256 _numOfMiningTime) public view returns (uint256) {
return miningReward[_numOfMiningTime];
}
| 10,227,488 |
pragma solidity ^0.5.0;
import "../../openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./BridgeToken.sol";
/**
* @title Chain33Bank
* @dev Manages the deployment and minting of ERC20 compatible BridgeTokens
* which represent assets based on the Chain33 blockchain.
**/
contract Chain33Bank {
using SafeMath for uint256;
uint256 public bridgeTokenCount;
mapping(address => bool) public bridgeTokenWhitelist;
mapping(bytes32 => bool) public bridgeTokenCreated;
mapping(bytes32 => Chain33Deposit) chain33Deposits;
mapping(bytes32 => Chain33Burn) chain33Burns;
mapping(address => DepositBurnCount) depositBurnCounts;
mapping(bytes32 => address) public token2address;
struct Chain33Deposit {
bytes chain33Sender;
address payable ethereumRecipient;
address bridgeTokenAddress;
uint256 amount;
bool exist;
uint256 nonce;
}
struct DepositBurnCount {
uint256 depositCount;
uint256 burnCount;
}
struct Chain33Burn {
bytes chain33Sender;
address payable ethereumOwner;
address bridgeTokenAddress;
uint256 amount;
uint256 nonce;
}
/*
* @dev: Event declarations
*/
event LogNewBridgeToken(
address _token,
string _symbol
);
event LogBridgeTokenMint(
address _token,
string _symbol,
uint256 _amount,
address _beneficiary
);
event LogChain33TokenBurn(
address _token,
string _symbol,
uint256 _amount,
address _ownerFrom,
bytes _chain33Receiver,
uint256 _nonce
);
/*
* @dev: Modifier to make sure this symbol not created now
*/
modifier notCreated(string memory _symbol)
{
require(
!hasBridgeTokenCreated(_symbol),
"The symbol has been created already"
);
_;
}
/*
* @dev: Modifier to make sure this symbol not created now
*/
modifier created(string memory _symbol)
{
require(
hasBridgeTokenCreated(_symbol),
"The symbol has not been created yet"
);
_;
}
/*
* @dev: Constructor, sets bridgeTokenCount
*/
constructor () public {
bridgeTokenCount = 0;
}
/*
* @dev: check whether this symbol has been created yet or not
*
* @param _symbol: token symbol
* @return: true or false
*/
function hasBridgeTokenCreated(string memory _symbol) public view returns(bool) {
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
return bridgeTokenCreated[symHash];
}
/*
* @dev: Creates a new Chain33Deposit with a unique ID
*
* @param _chain33Sender: The sender's Chain33 address in bytes.
* @param _ethereumRecipient: The intended recipient's Ethereum address.
* @param _token: The currency type
* @param _amount: The amount in the deposit.
* @return: The newly created Chain33Deposit's unique id.
*/
function newChain33Deposit(
bytes memory _chain33Sender,
address payable _ethereumRecipient,
address _token,
uint256 _amount
)
internal
returns(bytes32)
{
DepositBurnCount memory depositBurnCount = depositBurnCounts[_token];
depositBurnCount.depositCount = depositBurnCount.depositCount.add(1);
depositBurnCounts[_token] = depositBurnCount;
bytes32 depositID = keccak256(
abi.encodePacked(
_chain33Sender,
_ethereumRecipient,
_token,
_amount,
depositBurnCount.depositCount
)
);
chain33Deposits[depositID] = Chain33Deposit(
_chain33Sender,
_ethereumRecipient,
_token,
_amount,
true,
depositBurnCount.depositCount
);
return depositID;
}
/*
* @dev: Creates a new Chain33Burn with a unique ID
*
* @param _chain33Sender: The sender's Chain33 address in bytes.
* @param _ethereumOwner: The owner's Ethereum address.
* @param _token: The token Address
* @param _amount: The amount to be burned.
* @param _nonce: The nonce indicates the burn count for this token
* @return: The newly created Chain33Burn's unique id.
*/
function newChain33Burn(
bytes memory _chain33Sender,
address payable _ethereumOwner,
address _token,
uint256 _amount,
uint256 nonce
)
internal
returns(bytes32)
{
bytes32 burnID = keccak256(
abi.encodePacked(
_chain33Sender,
_ethereumOwner,
_token,
_amount,
nonce
)
);
chain33Burns[burnID] = Chain33Burn(
_chain33Sender,
_ethereumOwner,
_token,
_amount,
nonce
);
return burnID;
}
/*
* @dev: Deploys a new BridgeToken contract
*
* @param _symbol: The BridgeToken's symbol
*/
function deployNewBridgeToken(
string memory _symbol
)
internal
notCreated(_symbol)
returns(address)
{
bridgeTokenCount = bridgeTokenCount.add(1);
// Deploy new bridge token contract
BridgeToken newBridgeToken = (new BridgeToken)(_symbol);
// Set address in tokens mapping
address newBridgeTokenAddress = address(newBridgeToken);
bridgeTokenWhitelist[newBridgeTokenAddress] = true;
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
bridgeTokenCreated[symHash] = true;
depositBurnCounts[newBridgeTokenAddress] = DepositBurnCount(
uint256(0),
uint256(0));
token2address[symHash] = newBridgeTokenAddress;
emit LogNewBridgeToken(
newBridgeTokenAddress,
_symbol
);
return newBridgeTokenAddress;
}
/*
* @dev: Mints new chain33 tokens
*
* @param _chain33Sender: The sender's Chain33 address in bytes.
* @param _ethereumRecipient: The intended recipient's Ethereum address.
* @param _chain33TokenAddress: The currency type
* @param _symbol: chain33 token symbol
* @param _amount: number of chain33 tokens to be minted
*/
function mintNewBridgeTokens(
bytes memory _chain33Sender,
address payable _intendedRecipient,
address _bridgeTokenAddress,
string memory _symbol,
uint256 _amount
)
internal
{
// Must be whitelisted bridge token
require(
bridgeTokenWhitelist[_bridgeTokenAddress],
"Token must be a whitelisted bridge token"
);
// Mint bridge tokens
require(
BridgeToken(_bridgeTokenAddress).mint(
_intendedRecipient,
_amount
),
"Attempted mint of bridge tokens failed"
);
newChain33Deposit(
_chain33Sender,
_intendedRecipient,
_bridgeTokenAddress,
_amount
);
emit LogBridgeTokenMint(
_bridgeTokenAddress,
_symbol,
_amount,
_intendedRecipient
);
}
/*
* @dev: Burn chain33 tokens
*
* @param _from: The address to be burned from
* @param _chain33Receiver: The receiver's Chain33 address in bytes.
* @param _chain33TokenAddress: The token address of chain33 asset issued on ethereum
* @param _amount: number of chain33 tokens to be minted
*/
function burnChain33Tokens(
address payable _from,
bytes memory _chain33Receiver,
address _chain33TokenAddress,
uint256 _amount
)
internal
{
// Must be whitelisted bridge token
require(
bridgeTokenWhitelist[_chain33TokenAddress],
"Token must be a whitelisted bridge token"
);
// burn bridge tokens
BridgeToken bridgeTokenInstance = BridgeToken(_chain33TokenAddress);
bridgeTokenInstance.burnFrom(_from, _amount);
DepositBurnCount memory depositBurnCount = depositBurnCounts[_chain33TokenAddress];
require(
depositBurnCount.burnCount + 1 > depositBurnCount.burnCount,
"burn nonce is not available"
);
depositBurnCount.burnCount = depositBurnCount.burnCount.add(1);
depositBurnCounts[_chain33TokenAddress] = depositBurnCount;
newChain33Burn(
_chain33Receiver,
_from,
_chain33TokenAddress,
_amount,
depositBurnCount.burnCount
);
emit LogChain33TokenBurn(
_chain33TokenAddress,
bridgeTokenInstance.symbol(),
_amount,
_from,
_chain33Receiver,
depositBurnCount.burnCount
);
}
/*
* @dev: Checks if an individual Chain33Deposit exists.
*
* @param _id: The unique Chain33Deposit's id.
* @return: Boolean indicating if the Chain33Deposit exists in memory.
*/
function isLockedChain33Deposit(
bytes32 _id
)
internal
view
returns(bool)
{
return(chain33Deposits[_id].exist);
}
/*
* @dev: Gets an item's information
*
* @param _Id: The item containing the desired information.
* @return: Sender's address.
* @return: Recipient's address in bytes.
* @return: Token address.
* @return: Amount of ethereum/erc20 in the item.
* @return: Unique nonce of the item.
*/
function getChain33Deposit(
bytes32 _id
)
internal
view
returns(bytes memory, address payable, address, uint256)
{
Chain33Deposit memory deposit = chain33Deposits[_id];
return(
deposit.chain33Sender,
deposit.ethereumRecipient,
deposit.bridgeTokenAddress,
deposit.amount
);
}
function getToken2address(string memory _symbol)
created(_symbol)
public view returns(address)
{
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
return token2address[symHash];
}
}
|
: Creates a new Chain33Deposit with a unique ID _chain33Sender: The sender's Chain33 address in bytes. _ethereumRecipient: The intended recipient's Ethereum address. _token: The currency type _amount: The amount in the deposit. return: The newly created Chain33Deposit's unique id./
|
function newChain33Deposit(
bytes memory _chain33Sender,
address payable _ethereumRecipient,
address _token,
uint256 _amount
)
internal
returns(bytes32)
{
DepositBurnCount memory depositBurnCount = depositBurnCounts[_token];
depositBurnCount.depositCount = depositBurnCount.depositCount.add(1);
depositBurnCounts[_token] = depositBurnCount;
bytes32 depositID = keccak256(
abi.encodePacked(
_chain33Sender,
_ethereumRecipient,
_token,
_amount,
depositBurnCount.depositCount
)
);
chain33Deposits[depositID] = Chain33Deposit(
_chain33Sender,
_ethereumRecipient,
_token,
_amount,
true,
depositBurnCount.depositCount
);
return depositID;
}
| 12,752,952 |
./partial_match/1/0x3EB9D4F9848b759D2aB5947cE84cdA3fa75F3cca/sources/contracts/Land/NemoLand.sol
|
Listing `_id` for sale _id Id of land to put on sale amount Price for sale currencyType currency Type in which NFT owner wants to sell theis NFT/
|
function allowBuy(
uint256 _id,
uint256 amount,
uint256 currencyType
) external {
require(msg.sender == ownerOf(_id), "Not an Owner");
require(amount > 0, "Invalid Price");
require(tokenIdToPrice[_id].price == 0, "Already On sale");
tokensOnSale.push(_id);
tokenIdToPrice[_id] = OnSaleLand(amount, msg.sender, currencyType);
emit AllowBuy(msg.sender, _id, amount, currencyType);
}
| 9,275,924 |
/**
*Submitted for verification at Etherscan.io on 2021-02-19
*/
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
// 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;
}
}
// Dependency 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;
}
}
// Dependency 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);
}
}
}
}
// Dependency file: contracts/trusttoken/common/ProxyStorage.sol
// pragma solidity 0.6.10;
/**
* All storage must be declared here
* New storage must be appended to the end
* Never remove items from this list
*/
contract ProxyStorage {
bool initalized;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(uint144 => uint256) attributes_Depricated;
address owner_;
address pendingOwner_;
mapping(address => address) public delegates; // A record of votes checkpoints for each account, by index
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint32 fromBlock;
uint96 votes;
}
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; // A record of votes checkpoints for each account, by index
mapping(address => uint32) public numCheckpoints; // The number of checkpoints for each account
mapping(address => uint256) public nonces;
/* Additionally, we have several keccak-based storage locations.
* If you add more keccak-based storage mappings, such as mappings, you must document them here.
* If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision.
* A preimage collision can be used to attack the contract by treating one storage location as another,
* which would always be a critical issue.
* Carefully examine future keccak-based storage to ensure there can be no preimage collisions.
*******************************************************************************************************
** length input usage
*******************************************************************************************************
** 19 "trueXXX.proxy.owner" Proxy Owner
** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner
** 28 "trueXXX.proxy.implementation" Proxy Implementation
** 64 uint256(address),uint256(1) balanceOf
** 64 uint256(address),keccak256(uint256(address),uint256(2)) allowance
** 64 uint256(address),keccak256(bytes32,uint256(3)) attributes
**/
}
// Dependency file: contracts/trusttoken/common/ERC20.sol
/**
* @notice This is a copy of openzeppelin ERC20 contract with removed state variables.
* Removing state variables has been necessary due to proxy pattern usage.
* Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol:
* - Remove state variables _name, _symbol, _decimals
* - Use state variables balances, allowances, totalSupply from ProxyStorage
* - Remove constructor
* - Solidity version changed from ^0.6.0 to 0.6.10
* - Contract made abstract
* - Remove inheritance from IERC20 because of ProxyStorage name conflicts
*
* See also: ClaimableOwnable.sol and ProxyStorage.sol
*/
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol";
// prettier-ignore
/**
* @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}.
*/
abstract contract ERC20 is ProxyStorage, Context {
using SafeMath for uint256;
using Address for address;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the name of the token.
*/
function name() public virtual pure returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public virtual pure returns (string memory);
/**
* @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 virtual pure returns (uint8) {
return 18;
}
/**
* @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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual 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 returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance[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, allowance[_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, allowance[_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);
balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance");
balanceOf[recipient] = balanceOf[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);
balanceOf[account] = balanceOf[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);
balanceOf[account] = balanceOf[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");
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @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].
*/
// solhint-disable-next-line no-empty-blocks
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// Dependency file: contracts/governance/interface/IVoteToken.sol
// pragma solidity ^0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVoteToken {
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
function getCurrentVotes(address account) external view returns (uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
interface IVoteTokenWithERC20 is IVoteToken, IERC20 {}
// Dependency file: contracts/governance/VoteToken.sol
// AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/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.
//
// Ctrl+f for OLD to see all the modifications.
// pragma solidity 0.6.10;
// import {ERC20} from "contracts/trusttoken/common/ERC20.sol";
// import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol";
/**
* @title VoteToken
* @notice Custom token which tracks voting power for governance
* @dev This is an abstraction of a fork of the Compound governance contract
* VoteToken is used by TRU and stkTRU to allow tracking voting power
* Checkpoints are created every time state is changed which record voting power
* Inherits standard ERC20 behavior
*/
abstract contract VoteToken is ERC20, IVoteToken {
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function delegate(address delegatee) public override {
return _delegate(msg.sender, delegatee);
}
/**
* @dev Delegate votes using signature
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public override {
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("", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TrustToken::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TrustToken::delegateBySig: invalid nonce");
require(now <= expiry, "TrustToken::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @dev Get current voting power for an account
* @param account Account to get voting power for
* @return Voting power for an account
*/
function getCurrentVotes(address account) public virtual override view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @dev Get voting power at a specific block for an account
* @param account Account to get voting power for
* @param blockNumber Block to get voting power at
* @return Voting power for an account at specific block
*/
function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) {
require(blockNumber < block.number, "TrustToken::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;
}
/**
* @dev Internal function to delegate voting power to an account
* @param delegator Account to delegate votes from
* @param delegatee Account to delegate votes to
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
// OLD: uint96 delegatorBalance = balanceOf(delegator);
uint96 delegatorBalance = safe96(_balanceOf(delegator), "StkTruToken: uint96 overflow");
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _balanceOf(address account) internal view virtual returns (uint256) {
return balanceOf[account];
}
function _transfer(
address _from,
address _to,
uint256 _value
) internal virtual override {
super._transfer(_from, _to, _value);
_moveDelegates(delegates[_from], delegates[_to], safe96(_value, "StkTruToken: uint96 overflow"));
}
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
_moveDelegates(address(0), delegates[account], safe96(amount, "StkTruToken: uint96 overflow"));
}
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_moveDelegates(delegates[account], address(0), safe96(amount, "StkTruToken: uint96 overflow"));
}
/**
* @dev internal function to move delegates between accounts
*/
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, "TrustToken::_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, "TrustToken::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @dev internal function to write a checkpoint for voting power
*/
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "TrustToken::_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);
}
/**
* @dev internal function to convert from uint256 to uint32
*/
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/**
* @dev internal function to convert from uint256 to uint96
*/
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
/**
* @dev internal safe math function to add two uint96 numbers
*/
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev internal safe math function to subtract two uint96 numbers
*/
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev internal function to get chain ID
*/
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// Dependency file: contracts/trusttoken/common/ClaimableContract.sol
// pragma solidity 0.6.10;
// import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol";
/**
* @title ClaimableContract
* @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin.
and provides basic authorization control functions. Inherits storage layout of
ProxyStorage.
*/
contract ClaimableContract is ProxyStorage {
function owner() public view returns (address) {
return owner_;
}
function pendingOwner() public view returns (address) {
return pendingOwner_;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner_ = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner_, "only owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner_);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner_ = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
address _pendingOwner = pendingOwner_;
emit OwnershipTransferred(owner_, _pendingOwner);
owner_ = _pendingOwner;
pendingOwner_ = address(0);
}
}
// Dependency file: contracts/trusttoken/TimeLockedToken.sol
// pragma solidity 0.6.10;
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import {VoteToken} from "contracts/governance/VoteToken.sol";
// import {ClaimableContract} from "contracts/trusttoken/common/ClaimableContract.sol";
/**
* @title TimeLockedToken
* @notice Time Locked ERC20 Token
* @author Harold Hyatt
* @dev Contract which gives the ability to time-lock tokens
*
* The registerLockup() function allows an account to transfer
* its tokens to another account, locking them according to the
* distribution epoch periods
*
* By overriding the balanceOf(), transfer(), and transferFrom()
* functions in ERC20, an account can show its full, post-distribution
* balance but only transfer or spend up to an allowed amount
*
* Every time an epoch passes, a portion of previously non-spendable tokens
* are allowed to be transferred, and after all epochs have passed, the full
* account balance is unlocked
*/
abstract contract TimeLockedToken is VoteToken, ClaimableContract {
using SafeMath for uint256;
// represents total distribution for locked balances
mapping(address => uint256) distribution;
// start of the lockup period
// Friday, July 24, 2020 4:58:31 PM GMT
uint256 constant LOCK_START = 1595609911;
// length of time to delay first epoch
uint256 constant FIRST_EPOCH_DELAY = 30 days;
// how long does an epoch last
uint256 constant EPOCH_DURATION = 90 days;
// number of epochs
uint256 constant TOTAL_EPOCHS = 8;
// registry of locked addresses
address public timeLockRegistry;
// allow unlocked transfers to special account
bool public returnsLocked;
modifier onlyTimeLockRegistry() {
require(msg.sender == timeLockRegistry, "only TimeLockRegistry");
_;
}
/**
* @dev Set TimeLockRegistry address
* @param newTimeLockRegistry Address of TimeLockRegistry contract
*/
function setTimeLockRegistry(address newTimeLockRegistry) external onlyOwner {
require(newTimeLockRegistry != address(0), "cannot be zero address");
require(newTimeLockRegistry != timeLockRegistry, "must be new TimeLockRegistry");
timeLockRegistry = newTimeLockRegistry;
}
/**
* @dev Permanently lock transfers to return address
* Lock returns so there isn't always a way to send locked tokens
*/
function lockReturns() external onlyOwner {
returnsLocked = true;
}
/**
* @dev Transfer function which includes unlocked tokens
* Locked tokens can always be transfered back to the returns address
* Transferring to owner allows re-issuance of funds through registry
*
* @param _from The address to send tokens from
* @param _to The address that will receive the tokens
* @param _value The amount of tokens to be transferred
*/
function _transfer(
address _from,
address _to,
uint256 _value
) internal virtual override {
require(balanceOf[_from] >= _value, "insufficient balance");
// transfers to owner proceed as normal when returns allowed
if (!returnsLocked && _to == owner_) {
transferToOwner(_from, _value);
return;
}
// check if enough unlocked balance to transfer
require(unlockedBalance(_from) >= _value, "attempting to transfer locked funds");
super._transfer(_from, _to, _value);
}
/**
* @dev Transfer tokens to owner. Used only when returns allowed.
* @param _from The address to send tokens from
* @param _value The amount of tokens to be transferred
*/
function transferToOwner(address _from, uint256 _value) internal {
uint256 unlocked = unlockedBalance(_from);
if (unlocked < _value) {
// We want to have unlocked = value, i.e.
// value = balance - distribution * epochsLeft / totalEpochs
// distribution = (balance - value) * totalEpochs / epochsLeft
distribution[_from] = balanceOf[_from].sub(_value).mul(TOTAL_EPOCHS).div(epochsLeft());
}
super._transfer(_from, owner_, _value);
}
/**
* @dev Check if amount we want to burn is unlocked before burning
* @param _from The address whose tokens will burn
* @param _value The amount of tokens to be burnt
*/
function _burn(address _from, uint256 _value) internal override {
require(balanceOf[_from] >= _value, "insufficient balance");
require(unlockedBalance(_from) >= _value, "attempting to burn locked funds");
super._burn(_from, _value);
}
/**
* @dev Transfer tokens to another account under the lockup schedule
* Emits a transfer event showing a transfer to the recipient
* Only the registry can call this function
* @param receiver Address to receive the tokens
* @param amount Tokens to be transferred
*/
function registerLockup(address receiver, uint256 amount) external onlyTimeLockRegistry {
require(balanceOf[msg.sender] >= amount, "insufficient balance");
// add amount to locked distribution
distribution[receiver] = distribution[receiver].add(amount);
// transfer to recipient
_transfer(msg.sender, receiver, amount);
}
/**
* @dev Get locked balance for an account
* @param account Account to check
* @return Amount locked
*/
function lockedBalance(address account) public view returns (uint256) {
// distribution * (epochsLeft / totalEpochs)
return distribution[account].mul(epochsLeft()).div(TOTAL_EPOCHS);
}
/**
* @dev Get unlocked balance for an account
* @param account Account to check
* @return Amount that is unlocked and available eg. to transfer
*/
function unlockedBalance(address account) public view returns (uint256) {
// totalBalance - lockedBalance
return balanceOf[account].sub(lockedBalance(account));
}
function _balanceOf(address account) internal override view returns (uint256) {
return unlockedBalance(account);
}
/*
* @dev Get number of epochs passed
* @return Value between 0 and 8 of lockup epochs already passed
*/
function epochsPassed() public view returns (uint256) {
// return 0 if timestamp is lower than start time
if (block.timestamp < LOCK_START) {
return 0;
}
// how long it has been since the beginning of lockup period
uint256 timePassed = block.timestamp.sub(LOCK_START);
// 1st epoch is FIRST_EPOCH_DELAY longer; we check to prevent subtraction underflow
if (timePassed < FIRST_EPOCH_DELAY) {
return 0;
}
// subtract the FIRST_EPOCH_DELAY, so that we can count all epochs as lasting EPOCH_DURATION
uint256 totalEpochsPassed = timePassed.sub(FIRST_EPOCH_DELAY).div(EPOCH_DURATION);
// epochs don't count over TOTAL_EPOCHS
if (totalEpochsPassed > TOTAL_EPOCHS) {
return TOTAL_EPOCHS;
}
return totalEpochsPassed;
}
function epochsLeft() public view returns (uint256) {
return TOTAL_EPOCHS.sub(epochsPassed());
}
/**
* @dev Get timestamp of next epoch
* Will revert if all epochs have passed
* @return Timestamp of when the next epoch starts
*/
function nextEpoch() public view returns (uint256) {
// get number of epochs passed
uint256 passed = epochsPassed();
// if all epochs passed, return
if (passed == TOTAL_EPOCHS) {
// return INT_MAX
return uint256(-1);
}
// if no epochs passed, return latest epoch + delay + standard duration
if (passed == 0) {
return latestEpoch().add(FIRST_EPOCH_DELAY).add(EPOCH_DURATION);
}
// otherwise return latest epoch + epoch duration
return latestEpoch().add(EPOCH_DURATION);
}
/**
* @dev Get timestamp of latest epoch
* @return Timestamp of when the current epoch has started
*/
function latestEpoch() public view returns (uint256) {
// get number of epochs passed
uint256 passed = epochsPassed();
// if no epochs passed, return lock start time
if (passed == 0) {
return LOCK_START;
}
// accounts for first epoch being longer
// lockStart + firstEpochDelay + (epochsPassed * epochDuration)
return LOCK_START.add(FIRST_EPOCH_DELAY).add(passed.mul(EPOCH_DURATION));
}
/**
* @dev Get timestamp of final epoch
* @return Timestamp of when the last epoch ends and all funds are released
*/
function finalEpoch() public pure returns (uint256) {
// lockStart + firstEpochDelay + (epochDuration * totalEpochs)
return LOCK_START.add(FIRST_EPOCH_DELAY).add(EPOCH_DURATION.mul(TOTAL_EPOCHS));
}
/**
* @dev Get timestamp of locking period start
* @return Timestamp of locking period start
*/
function lockStart() public pure returns (uint256) {
return LOCK_START;
}
}
// Root file: contracts/trusttoken/TrustToken.sol
pragma solidity 0.6.10;
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {TimeLockedToken} from "contracts/trusttoken/TimeLockedToken.sol";
/**
* @title TrustToken
* @dev The TrustToken contract is a claimable contract where the
* owner can only mint or transfer ownership. TrustTokens use 8 decimals
* in order to prevent rewards from getting stuck in the remainder on division.
* Tolerates dilution to slash stake and accept rewards.
*/
contract TrustToken is TimeLockedToken {
using SafeMath for uint256;
uint256 constant MAX_SUPPLY = 145000000000000000;
/**
* @dev initialize trusttoken and give ownership to sender
* This is necessary to set ownership for proxy
*/
function initialize() public {
require(!initalized, "already initialized");
owner_ = msg.sender;
initalized = true;
}
/**
* @dev mint TRU
* Can never mint more than MAX_SUPPLY = 1.45 billion
*/
function mint(address _to, uint256 _amount) external onlyOwner {
if (totalSupply.add(_amount) <= MAX_SUPPLY) {
_mint(_to, _amount);
} else {
revert("Max supply exceeded");
}
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function decimals() public override pure returns (uint8) {
return 8;
}
function rounding() public pure returns (uint8) {
return 8;
}
function name() public override pure returns (string memory) {
return "TrueFi";
}
function symbol() public override pure returns (string memory) {
return "TRU";
}
}
|
Permanently lock transfers to return address Lock returns so there isn't always a way to send locked tokens/
|
function lockReturns() external onlyOwner {
returnsLocked = true;
}
| 2,155,509 |
/**
*Submitted for verification at Etherscan.io on 2020-08-26
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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) {
// 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 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/utils/EnumerableSet.sol
pragma solidity ^0.6.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.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;
// 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];
}
// 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));
}
}
// 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/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: @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 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/AntsToken.sol
pragma solidity 0.6.12;
// AntsToken with Governance.
contract AntsToken is ERC20("AntsToken", "ANTS"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
require(totalSupply() < 1e26 , "Totoal supply overflow"); // 1e8 ** decimal
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 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 A record of states for signing / validating signatures
mapping (address => uint) 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, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @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,
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), "ANTS::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "ANTS::delegateBySig: invalid nonce");
require(now <= expiry, "ANTS::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 (uint256)
{
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 (uint256)
{
require(blockNumber < block.number, "ANTS::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); // balance of underlying ANTSs (not scaled);
_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, "ANTS::_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(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to AntsSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// AntsSwap must mint EXACTLY the same amount of AntsSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Ants. He can make Ants and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 lockBlock; // lockBlock
uint256 lockedAmount; // lockedAmount
uint256 pending; // pending amount, convert to amount via withdraw
//
// We do some fancy math here. Basically, any point in time, the amount of ANTSs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accAntsPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accAntsPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
bool isSingle; // sigle token mint
uint256 allocPoint; // How many allocation points assigned to this pool. ANTSs to distribute per block.
uint256 lastRewardBlock; // Last block number that ANTSs distribution occurs.
uint256 accAntsPerShare; // Accumulated ANTSs per share, times 1e12. See below.
}
// The ANTS TOKEN!
AntsToken public ants;
// Dev address.
address public devaddr;
// Block number when bonus ANTS period ends.
uint256 public bonusEndBlock;
// Token locked block length
uint256 public halvedBlock;
uint256 public halvedBlockLength = 2_000_000;
// Token locked block length
uint256 public antsLockedBlock;
// ANTS tokens created per block.
uint256 public antsPerBlock;
// Bonus muliplier for early ants makers.
uint256 public constant BONUS_MULTIPLIER = 5;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Invite user
mapping (address => uint256) public balanceInvite;
mapping (address => address) public userInvite;
mapping (address => bool) public userInviteAble;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when ANTS mining starts.
uint256 public startBlock;
event Invite(address indexed inviter, address indexed invitee);
event InviteReward(address indexed inviter, address indexed invitee, uint256 amount);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
AntsToken _ants,
address _devaddr,
uint256 _antsPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
ants = _ants;
devaddr = _devaddr;
antsPerBlock = _antsPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
halvedBlock = _startBlock;
antsLockedBlock = 200_000;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken , bool _isSingle, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
isSingle: _isSingle,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAntsPerShare: 0
}));
}
// Update the given pool's ANTS allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending ANTSs on frontend.
function pendingAnts(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see pending ANTSs on frontend.
function totalPendingAnts(uint256 _pid, address _user) external view returns (uint256 , uint256 ) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
uint256 pending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt).add(user.pending);
uint256 reward = 0;
if(userInvite[_user] != address(0) && userInvite[_user] != address(this) ) {
reward = pending.mul(1).div(20);
}
return (pending, reward);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
// UserInfo storage dev = userInfo[_pid][devaddr];
// dev.pending = dev.pending.add(antsReward.div(20));
ants.mint(devaddr, antsReward.div(20));
ants.mint(address(this), antsReward);
pool.accAntsPerShare = pool.accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
if(block.number >= halvedBlockLength.add(halvedBlock)) {
halvedBlock = block.number;
antsPerBlock = antsPerBlock.div(2);
}
}
function updateLockBlock(uint256 _pid, uint256 _amount) internal {
UserInfo storage user = userInfo[_pid][msg.sender];
if(user.lockBlock == 0) {//
user.lockBlock = block.number;
}else {
// (b-a) * amountB/(amountA + amountbB)
user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock);
}
}
function setInviter(address _inviter) public {
require(_inviter != address(0), "Inviter not null");
require(_inviter != msg.sender, "Inviter cannot be self");
require(userInviteAble[_inviter], "Inviter invalid");
userInvite[msg.sender] = _inviter;
}
function depositWithInvite(uint256 _pid, uint256 _amount, address _inviter) public {
if( userInvite[msg.sender] == address(0) ) {
require(_inviter != address(0), "Inviter not null");
require(_inviter != msg.sender, "Inviter cannot be self");
require(userInviteAble[_inviter], "Inviter invalid");
userInvite[msg.sender] = _inviter;
emit Invite(_inviter, msg.sender);
}
deposit(_pid, _amount);
}
// Deposit LP tokens to MasterChef for ANTS allocation.
function deposit(uint256 _pid, uint256 _amount) public {
if(_amount > 0 && !userInviteAble[msg.sender]) {
userInviteAble[msg.sender] = true;
}
if(userInvite[msg.sender] == address(0) ) {
userInvite[msg.sender] = address(this);
}
updateLockBlock(_pid, _amount);
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt);
// safeAntsTransfer(msg.sender, pending);
user.pending = user.pending.add(pending);
}
if(pool.isSingle) {
chefSafeTransferFrom(pool.lpToken, address(msg.sender), address(this), _amount);
}else {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt);
user.pending = user.pending.add(pending);
//pending ++
//exec safeAntsTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
if(pool.isSingle) {
chefSafeTransfer(pool.lpToken, address(msg.sender), _amount);
}else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
emit Withdraw(msg.sender, _pid, _amount);
}
function withdrawInviteReward() public {
ants.mint(msg.sender, balanceInvite[msg.sender] );
balanceInvite[msg.sender] = 0;
}
function withdrawToken(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt);
user.pending = pending.add(user.pending);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
bool invited = userInvite[msg.sender] != address(0) && userInvite[msg.sender] != address(this);
uint256 availablePending = invited? user.pending.mul(21).div(20) : user.pending;
if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock ) {
availablePending = availablePending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock);
}
if(availablePending > 0 ){
//update lockedNumber
//block.number.sub(user.lockBlock).mul(withdrawAmount).div(availablePending).add(user.lockBlock);
if(invited) {
//mint invitee reward
ants.mint(msg.sender, availablePending.mul(1).div(21));
availablePending = availablePending.mul(20).div(21); // avaliable = avaliable * 1.05
//record inviter reward
address inviter = userInvite[msg.sender];
uint256 reward = availablePending.div(10);
balanceInvite[inviter] = balanceInvite[inviter].add(reward);
emit InviteReward(inviter, msg.sender, reward);
}
safeAntsTransfer(msg.sender, availablePending);
user.pending = user.pending.sub(availablePending);
user.lockBlock = block.number;
}
if(user.amount == 0 && user.pending == 0) {
user.lockBlock = 0;
}
}
function calcuAvalible(uint256 _pid , address _user) external view returns (uint256 ) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
uint256 addPending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt);
uint256 totalPending = user.pending.add(addPending);
bool invited = userInvite[_user] != address(0) && userInvite[_user] != address(this) ;
uint256 pending = invited? totalPending.mul(21).div(20) : totalPending;
if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock) {
return pending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock);
}else {
return pending;
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if(pool.isSingle) {
chefSafeTransfer(pool.lpToken, address(msg.sender), user.amount);
}else {
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
}
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe ants transfer function, just in case if rounding error causes pool to not have enough ANTSs.
function safeAntsTransfer(address _to, uint256 _amount) internal {
uint256 antsBal = ants.balanceOf(address(this));
if (_amount > antsBal) {
ants.transfer(_to, antsBal);
} else {
ants.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function chefSafeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function chefSafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
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");
}
}
}
|
View function to see pending ANTSs on frontend.
|
function pendingAnts(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt);
}
| 10,403,690 |
pragma solidity ^0.4.23;
// File: 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 public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @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.
*/
constructor() 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 {
owner.transfer(this.balance);
}
}
// File: openzeppelin-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 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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @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];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @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;
}
}
// File: contracts/ChartToken.sol
contract ChartToken is StandardToken, BurnableToken, Ownable, HasNoEther {
string public constant name = "BetOnChart token";
string public constant symbol = "CHART";
uint8 public constant decimals = 18; // 1 ether
bool public saleFinished;
address public saleAgent;
address private wallet;
/**
* @dev Event should be emited when sale agent changed
*/
event SaleAgent(address);
/**
* @dev ChartToken constructor
* All tokens supply will be assign to contract owner.
* @param _wallet Wallet to handle initial token emission.
*/
constructor(address _wallet) public {
require(_wallet != address(0));
totalSupply_ = 50*1e6*(1 ether);
saleFinished = false;
balances[_wallet] = totalSupply_;
wallet = _wallet;
saleAgent = address(0);
}
/**
* @dev Modifier to make a function callable only by owner or sale agent.
*/
modifier onlyOwnerOrSaleAgent() {
require(msg.sender == owner || msg.sender == saleAgent);
_;
}
/**
* @dev Modifier to make a function callable only when a sale is finished.
*/
modifier whenSaleFinished() {
require(saleFinished || msg.sender == saleAgent || msg.sender == wallet );
_;
}
/**
* @dev Modifier to make a function callable only when a sale is not finished.
*/
modifier whenSaleNotFinished() {
require(!saleFinished);
_;
}
/**
* @dev Set sale agent
* @param _agent The agent address which you want to set.
*/
function setSaleAgent(address _agent) public whenSaleNotFinished onlyOwner {
saleAgent = _agent;
emit SaleAgent(_agent);
}
/**
* @dev Handle ICO end
*/
function finishSale() public onlyOwnerOrSaleAgent {
saleAgent = address(0);
emit SaleAgent(saleAgent);
saleFinished = true;
}
/**
* @dev Overrides default ERC20
*/
function transfer(address _to, uint256 _value) public whenSaleFinished returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Overrides default ERC20
*/
function transferFrom(address _from, address _to, uint256 _value) public whenSaleFinished returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: contracts/lib/TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/lib/WhitelistedCrowdsale.sol
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
/**
* @dev Minimal contract to whitelisted addresses
*/
struct Contract
{
uint256 rate; // Token rate
uint256 minInvestment; // Minimal investment
}
mapping(address => bool) public whitelist;
mapping(address => Contract) public contracts;
/**
* @dev Reverts if beneficiary is not whitelisted.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Reverts if beneficiary is not invests minimal ether amount.
*/
modifier isMinimalInvestment(address _beneficiary, uint256 _weiAmount) {
require(_weiAmount >= contracts[_beneficiary].minInvestment);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
* @param _bonus Token bonus from 0% to 300%
* @param _minInvestment Minimal investment
*/
function addToWhitelist(address _beneficiary, uint16 _bonus, uint256 _minInvestment) external onlyOwner {
require(_bonus <= 300);
whitelist[_beneficiary] = true;
Contract storage beneficiaryContract = contracts[_beneficiary];
beneficiaryContract.rate = rate.add(rate.mul(_bonus).div(100));
beneficiaryContract.minInvestment = _minInvestment.mul(1 ether);
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
* @param _bonus Token bonus from 0% to 300%
* @param _minInvestment Minimal investment
*/
function addManyToWhitelist(address[] _beneficiaries, uint16 _bonus, uint256 _minInvestment) external onlyOwner {
require(_bonus <= 300);
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
Contract storage beneficiaryContract = contracts[_beneficiaries[i]];
beneficiaryContract.rate = rate.add(rate.mul(_bonus).div(100));
beneficiaryContract.minInvestment = _minInvestment.mul(1 ether);
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
isMinimalInvestment(_beneficiary, _weiAmount)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/**
* @dev The way in which ether is converted to tokens. Overrides default function.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
{
return _weiAmount.mul(contracts[msg.sender].rate);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
constructor(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
// File: contracts/ChartPresale.sol
contract ChartPresale is WhitelistedCrowdsale, AllowanceCrowdsale, TimedCrowdsale, CappedCrowdsale {
using SafeMath for uint256;
string public constant name = "BetOnChart token presale";
constructor(uint256 _rate, address _tokenWallet, address _ethWallet, ChartToken _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) public
Crowdsale(_rate, _ethWallet, _token)
AllowanceCrowdsale(_tokenWallet)
TimedCrowdsale(_openingTime, _closingTime)
CappedCrowdsale(_cap) {}
}
|
Overrides parent behavior by transferring tokens from wallet. _beneficiary Token purchaser _tokenAmount Amount of tokens purchased/
|
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
| 1,221,721 |
./partial_match/4/0x52889dEbc051C1078C19e8Ca3bB8E9229A9bAEF6/sources/DF9T.sol
|
Initialize market This function registers market conditions. arguments are verified by the 'validate' function./
|
function initialize(
string memory _settings,
uint256[] memory _conditions,
address[] memory _references,
string memory metadataBaseURI
) public override returns (bool) {
require(
validate(
_settings,
_conditions,
_references
)
);
require(initialized == false);
initialized = true;
startTime = _conditions[0];
endTime = _conditions[1];
reportTime = _conditions[2];
ticketPrice = _conditions[3];
round = _conditions[4];
usdt = IERC20(_references[0]);
oracle = _references[1];
df9 = DF9(_references[2]);
factory = msg.sender;
_setBaseMetadataURI(metadataBaseURI);
hashID = keccak256(
abi.encodePacked(
_settings,
_conditions,
_references
)
);
marketStatus = MarketStatus.BeforeTrading;
return true;
}
| 8,651,809 |
/**
*Submitted for verification at Etherscan.io on 2021-09-05
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// _______ ______ __ __ _______ _______ _______ _______ _______ _______ __ __ ___
// | || _ | | | | || || || | | || || || | | || |
// | || | || | |_| || _ ||_ _|| _ | | _ || _ || || |_| || |
// | || |_||_ | || |_| | | | | | | | | |_| || | | || || || |
// | _|| __ ||_ _|| ___| | | | |_| | | ___|| |_| || _|| || |
// | |_ | | | | | | | | | | | | | | | || |_ | _ || |
// |_______||___| |_| |___| |___| |___| |_______| |___| |_______||_______||__| |__||___|
//
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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 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);
}
}
}
}
/**
* @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);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function burn(uint256 burnQuantity) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @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 EnumerableMap {
// 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 MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @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) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @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) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @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._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.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) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._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) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// 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 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.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
/**
* @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];
// Equivalent to contains(set, value)
if (valueIndex != 0) {
// 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];
}
// 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));
}
}
contract Ownable {
address private _owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @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 onlyDeployer() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyDeployer` functions anymore. Can only be called by the current deployer.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external virtual onlyDeployer {
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) external virtual onlyDeployer {
require(_newOwner != newOwner);
require(_newOwner != _owner);
newOwner = _newOwner;
}
function acceptOwnership() external {
require(msg.sender == newOwner);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
newOwner = address(0);
}
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 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;
}
}
/**
* @title CryptoPochi - an interactive NFT project
*
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract Pochi is ReentrancyGuard, Ownable, ERC165, IERC721Enumerable, IERC721Metadata {
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
uint256 public constant MAX_NFT_SUPPLY = 1500;
uint256 public constant MAX_EARLY_ACCESS_SUPPLY = 750;
// This will be set after the collection is fully minted and before sealing the contract
string public PROVENANCE = "";
uint256 public EARLY_ACCESS_START_TIMESTAMP = 1630854000; // 2021-09-05 15:00:00 UTC
uint256 public SALE_START_TIMESTAMP = 1630940400; // 2021-09-06 15:00:00 UTC
// The unit here is per half hour. Price decreases in a step function every half hour
uint256 public SALE_DURATION = 12;
uint256 public SALE_DURATION_SEC_PER_STEP = 1800; // 30 minutes
uint256 public DUTCH_AUCTION_START_FEE = 8 ether;
uint256 public DUTCH_AUCTION_END_FEE = 2 ether;
uint256 public EARLY_ACCESS_MINT_FEE = 0.5 ether;
uint256 public earlyAccessMinted;
uint256 public POCHI_ACTION_PUBLIC_FEE = 0.01 ether;
uint256 public POCHI_ACTION_OWNER_FEE = 0 ether;
uint256 public constant POCHI_ACTION_PLEASE_JUMP = 1;
uint256 public constant POCHI_ACTION_PLEASE_SAY_SOMETHING = 2;
uint256 public constant POCHI_ACTION_PLEASE_GO_HAM = 3;
// Seal contracts for minting, provenance
bool public contractSealed;
// tokenId -> tokenHash
mapping(uint256 => bytes32) public tokenIdToHash;
// Early access for ham holders
mapping(address => uint256) public earlyAccessList;
string private _baseURI;
// 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 => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.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;
/*
* 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
*
* => 0x06fdde03 ^ 0x95d89b41 == 0x93254542
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542;
/*
* 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;
// Events
event NewTokenHash(uint256 indexed tokenId, bytes32 tokenHash);
event PochiAction(uint256 indexed timestamp, uint256 actionType, string actionText, string actionTarget, address indexed requester);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory finalName, string memory finalSymbol) {
_name = finalName;
_symbol = finalSymbol;
// 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 {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 {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() external view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Fetch all tokens owned by an address
*/
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
/**
* @dev Fetch all tokens and their tokenHash owned by an address
*/
function tokenHashesOfOwner(address _owner) external view returns (uint256[] memory, bytes32[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return (new uint256[](0), new bytes32[](0));
} else {
uint256[] memory result = new uint256[](tokenCount);
bytes32[] memory hashes = new bytes32[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
hashes[index] = tokenIdToHash[index];
}
return (result, hashes);
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) external view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Returns current token price
*/
function getNFTPrice() public view returns (uint256) {
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
uint256 count = totalSupply();
require(count < MAX_NFT_SUPPLY, "Sale has already ended");
uint256 elapsed = block.timestamp - SALE_START_TIMESTAMP;
if (elapsed >= SALE_DURATION * SALE_DURATION_SEC_PER_STEP) {
return DUTCH_AUCTION_END_FEE;
} else {
return (((SALE_DURATION * SALE_DURATION_SEC_PER_STEP - elapsed - 1) / SALE_DURATION_SEC_PER_STEP + 1) * (DUTCH_AUCTION_START_FEE - DUTCH_AUCTION_END_FEE)) / SALE_DURATION + DUTCH_AUCTION_END_FEE;
}
}
/**
* @dev Mint tokens and refund any excessive amount of ETH sent in
*/
function mintAndRefundExcess(uint256 numberOfNfts) external payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
require(numberOfNfts > 0, "Cannot mint 0 NFTs");
require(numberOfNfts <= 50, "Cannot mint more than 50 in 1 tx");
uint256 total = totalSupply();
require(total + numberOfNfts <= MAX_NFT_SUPPLY, "Sold out");
uint256 price = getNFTPrice();
require(msg.value >= numberOfNfts * price, "Ether value sent is insufficient");
// Effects
_safeMintWithHash(msg.sender, numberOfNfts, total);
if (msg.value > numberOfNfts * price) {
(bool success, ) = msg.sender.call{value: msg.value - numberOfNfts * price}("");
require(success, "Refund excess failed.");
}
}
/**
* @dev Mint early access tokens
*/
function mintEarlyAccess(uint256 numberOfNfts) external payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp < SALE_START_TIMESTAMP, "Early access is over");
require(block.timestamp >= EARLY_ACCESS_START_TIMESTAMP, "Early access has not started");
require(numberOfNfts > 0, "Cannot mint 0 NFTs");
require(numberOfNfts <= 50, "Cannot mint more than 50 in 1 tx");
uint256 total = totalSupply();
require(total + numberOfNfts <= MAX_NFT_SUPPLY, "Sold out");
require(earlyAccessMinted + numberOfNfts <= MAX_EARLY_ACCESS_SUPPLY, "No more early access tokens left");
require(earlyAccessList[msg.sender] >= numberOfNfts, "Invalid early access mint");
require(msg.value == numberOfNfts * EARLY_ACCESS_MINT_FEE, "Ether value sent is incorrect");
// Effects
earlyAccessList[msg.sender] = earlyAccessList[msg.sender] - numberOfNfts;
earlyAccessMinted = earlyAccessMinted + numberOfNfts;
_safeMintWithHash(msg.sender, numberOfNfts, total);
}
/**
* @dev Return if we are in the early access time period
*/
function isInEarlyAccess() external view returns (bool) {
return block.timestamp >= EARLY_ACCESS_START_TIMESTAMP && block.timestamp < SALE_START_TIMESTAMP;
}
/**
* @dev Interact with Pochi. Directly from Ethereum!
*/
function pochiAction(
uint256 actionType,
string calldata actionText,
string calldata actionTarget
) external payable {
if (balanceOf(msg.sender) > 0) {
require(msg.value >= POCHI_ACTION_OWNER_FEE, "Ether value sent is incorrect");
} else {
require(msg.value >= POCHI_ACTION_PUBLIC_FEE, "Ether value sent is incorrect");
}
emit PochiAction(block.timestamp, actionType, actionText, actionTarget, msg.sender);
}
/**
* @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 baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) external view virtual returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
// If there is no base URI, return the token id.
if (bytes(base).length == 0) {
return tokenId.toString();
}
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all");
_approve(to, tokenId);
}
/**
* @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) external virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, 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
) external virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, 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(msg.sender, 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 mint tokens, and assign tokenHash to the new tokens
*
* Emits a {NewTokenHash} event.
*/
function _safeMintWithHash(
address to,
uint256 numberOfNfts,
uint256 startingTokenId
) internal virtual {
for (uint256 i = 0; i < numberOfNfts; i++) {
uint256 tokenId = startingTokenId + i;
bytes32 tokenHash = keccak256(abi.encodePacked(tokenId, block.number, block.coinbase, block.timestamp, blockhash(block.number - 1), msg.sender));
tokenIdToHash[tokenId] = tokenHash;
_safeMint(to, tokenId, "");
emit NewTokenHash(tokenId, tokenHash);
}
}
/**
* @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);
_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);
_holderTokens[owner].remove(tokenId);
// Burn the token by reassigning owner to the null address
_tokenOwners.set(tokenId, address(0));
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 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(IERC721Receiver(to).onERC721Received.selector, msg.sender, 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 {}
/**
* @dev Deployer parameters
*/
function deployerSetParam(uint256 key, uint256 value) external onlyDeployer {
require(!contractSealed, "Contract sealed");
if (key == 0) {
EARLY_ACCESS_START_TIMESTAMP = value;
} else if (key == 1) {
SALE_START_TIMESTAMP = value;
} else if (key == 2) {
SALE_DURATION = value;
} else if (key == 3) {
SALE_DURATION_SEC_PER_STEP = value;
} else if (key == 10) {
EARLY_ACCESS_MINT_FEE = value;
} else if (key == 11) {
DUTCH_AUCTION_START_FEE = value;
} else if (key == 12) {
DUTCH_AUCTION_END_FEE = value;
} else if (key == 20) {
POCHI_ACTION_PUBLIC_FEE = value;
} else if (key == 21) {
POCHI_ACTION_OWNER_FEE = value;
} else {
revert();
}
}
/**
* @dev Add to the early access list
*/
function deployerAddEarlyAccess(address[] calldata recipients, uint256[] calldata limits) external onlyDeployer {
require(!contractSealed, "Contract sealed");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't add the null address");
earlyAccessList[recipients[i]] = limits[i];
}
}
/**
* @dev Remove from the early access list
*/
function deployerRemoveEarlyAccess(address[] calldata recipients) external onlyDeployer {
require(!contractSealed, "Contract sealed");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't remove the null address");
earlyAccessList[recipients[i]] = 0;
}
}
/**
* @dev Reserve dev tokens and air drop tokens to craft ham holders
*/
function deployerMintMultiple(address[] calldata recipients) external payable onlyDeployer {
require(!contractSealed, "Contract sealed");
uint256 total = totalSupply();
require(total + recipients.length <= MAX_NFT_SUPPLY, "Sold out");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't mint to null address");
_safeMintWithHash(recipients[i], 1, total + i);
}
}
/**
* @dev Deployer withdraws ether from this contract
*/
function deployerWithdraw(uint256 amount) external onlyDeployer {
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed.");
}
/**
* @dev Deployer withdraws ERC20s
*/
function deployerWithdraw20(IERC20 token) external onlyDeployer {
if (address(token) == 0x0000000000000000000000000000000000000000) {
payable(owner()).transfer(address(this).balance);
(bool success, ) = owner().call{value: address(this).balance}("");
require(success, "Transfer failed.");
} else {
token.transfer(owner(), token.balanceOf(address(this)));
}
}
/**
* @dev Deployer sets baseURI
*/
function deployerSetBaseURI(string memory finalBaseURI) external onlyDeployer {
_setBaseURI(finalBaseURI);
}
/**
* @dev Deployer sets PROVENANCE
*/
function deployerSetProvenance(string memory finalProvenance) external onlyDeployer {
require(!contractSealed, "Contract sealed");
PROVENANCE = finalProvenance;
}
/**
* @dev Seal this contract
*/
function deployerSealContract() external onlyDeployer {
require(bytes(PROVENANCE).length != 0, "PROVENANCE must be set first");
contractSealed = true;
}
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals Burn the token by reassigning owner to the null address
|
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.set(tokenId, address(0));
emit Transfer(owner, address(0), tokenId);
}
| 7,921,388 |
./partial_match/42/0xF22dbb8290D239125ca69bBBa96AED18d5f29966/sources/Maximillion.sol
|
msg.sender sends Ether to repay an account's borrow in a cEther market The provided Ether is applied towards the borrow balance, any excess is refunded borrower The address of the borrower account to repay on behalf of pEther_ The address of the cEther contract to repay in/
|
function repayBehalfExplicit(address borrower, PEther pEther_) public payable {
uint received = msg.value;
uint borrows = pEther_.borrowBalanceCurrent(borrower);
if (received > borrows) {
pEther_.repayBorrowBehalf.value(borrows)(borrower);
msg.sender.transfer(received - borrows);
pEther_.repayBorrowBehalf.value(received)(borrower);
}
}
| 3,386,597 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "hardhat/console.sol";
contract Presale is ReentrancyGuard, Ownable {
uint256 public constant DECIMALS = 18;
uint256 public constant DENOMINATOR = 10**DECIMALS;
uint256 public constant INITIAL_PRICE = (DENOMINATOR) / 7402; //Initial price 1 ETH == 7402 tokens
/**
* @dev price must be set with `DENOMINATOR` decimals
*/
uint256 public price = INITIAL_PRICE;
address payable public receiverOfEarnings;
IERC20Metadata public presaleToken;
uint8 internal tokenDecimals;
bool public paused;
event PriceChange(uint256 oldPrice, uint256 newPrice);
event BoughtWithBNB(uint256 amount);
/**
* @dev Throws is the presale is paused
*/
modifier notPaused() {
require(!paused, "Presale is paused");
_;
}
/**
* @dev Throws is presale is NOT paused
*/
modifier isPaused() {
require(paused, "Presale is not paused");
_;
}
/**
* @param _presaleToken adress of the token to be purchased through preslae
* @param _receiverOfEarnings address of the wallet to be allowed to withdraw the proceeds
*/
constructor(
address _presaleToken,
address payable _receiverOfEarnings
) {
require(
_receiverOfEarnings != address(0),
"Receiver wallet cannot be 0"
);
receiverOfEarnings = _receiverOfEarnings;
presaleToken = IERC20Metadata(_presaleToken);
tokenDecimals = presaleToken.decimals();
paused = true; //@dev start as paused
}
/**
* @notice Sets the address allowed to withdraw the proceeds from presale
* @param _receiverOfEarnings address of the reveiver
*/
function setReceiverOfEarnings(address payable _receiverOfEarnings)
external
onlyOwner
{
require(
_receiverOfEarnings != receiverOfEarnings,
"Receiver already configured"
);
require(_receiverOfEarnings != address(0), "Receiver cannot be 0");
receiverOfEarnings = _receiverOfEarnings;
}
/**
* @notice Sets new price for the presale token
* @param _price new price of the presale token - uses `DECIMALS` for precision
*/
function setPrice(uint256 _price) external onlyOwner {
require(_price != price, "New price cannot be same");
uint256 _oldPrice = price;
price = _price;
emit PriceChange(_oldPrice, _price);
}
/**
* @notice Releases presale tokens to the recipient
* @param _recipient recipient of the presale tokens
* @param _paidAmount amount paid by recipient
*/
function _releasePresaleTokens(
address _recipient,
uint256 _paidAmount
) internal {
uint256 tokensToReceive = calculateTokensToReceive(_paidAmount);
require(
tokensToReceive <= presaleToken.balanceOf(address(this)),
"Contract balance too low"
);
require(
presaleToken.transfer(_recipient, tokensToReceive),
"Token transfer failed"
);
}
receive() external payable {
buyTokensWithBNB();
}
/**
* @notice Allows purchase of presale tokens using BNB
*/
function buyTokensWithBNB()
public
payable
notPaused
nonReentrant
{
require(msg.value > 0, "No BNB sent");
_releasePresaleTokens(msg.sender, msg.value);
emit BoughtWithBNB(msg.value);
}
/**
* @notice Transfers collected funds to `receiverOfEarnings` address
*/
function withdraw() external {
require(
msg.sender == receiverOfEarnings,
"Sender not allowed to withdraw"
);
uint256 bnbBalance = address(this).balance;
if (bnbBalance > 0) {
payable(receiverOfEarnings).transfer(bnbBalance);
}
}
/**
* @notice Transfers all remaining `presaleToken` balance to owner when presale is over
*/
function rescuePresaleTokens() external onlyOwner isPaused {
uint256 balance = presaleToken.balanceOf(address(this));
require(balance > 0, "No tokens to rescue");
require(
presaleToken.transfer(owner(), balance),
"Token transfer failed"
);
}
/**
* @notice Calculates the amount of `presaleToken` based on the amount of `paidWithToken`
* @param _amount amount of `paidWithToken` used in purchase
*/
function calculateTokensToReceive(uint256 _amount)
public
view
returns (uint256)
{
uint256 amountToTransfer = (_amount * 10**tokenDecimals) / price;
return amountToTransfer;
}
/**
* @notice Pauses the presale
*/
function pause() external onlyOwner notPaused {
paused = true;
}
/**
* @notice Unpauses the presale
*/
function unpause() external onlyOwner isPaused {
paused = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// 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.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
// OpenZeppelin Contracts (last updated v4.5.0) (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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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
// 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;
}
}
|
Sets new price for the presale token _price new price of the presale token - uses `DECIMALS` for precision/
|
function setPrice(uint256 _price) external onlyOwner {
require(_price != price, "New price cannot be same");
uint256 _oldPrice = price;
price = _price;
emit PriceChange(_oldPrice, _price);
}
| 13,788,898 |
pragma solidity ^0.6.0;
import "./token.sol";
contract ERC20Manager {
address payable seller;
uint public price = 100 finney;
ETHC tokenContract;
constructor() public
{
seller = msg.sender;
}
modifier onlyOwner
{
require(
msg.sender == seller,
"Only owner can call this function."
);
_;
}
modifier isConfigured
{
require(
tokenContract != ETHC(0),
"Token is not configured yet"
);
_;
}
modifier gtPrice
{
require(msg.value >= price, "Value should be greater than price!");
_;
}
function config(address _tokenContract) public onlyOwner
{
tokenContract = ETHC(_tokenContract);
}
// get configured token name
function getTokenName() public view isConfigured returns (string memory)
{
return tokenContract.name();
}
// proxy balanceOf
function balanceOf(address addr) public view isConfigured returns (uint256)
{
return tokenContract.balanceOf(addr);
}
// swap token
function swap(uint256 amount) external isConfigured
{
require(tokenContract.balanceOf(msg.sender) > amount);
tokenContract.transferFrom(msg.sender, seller, amount);
msg.sender.transfer(amount * price);
}
// swap ether
// function swap() external payable isConfigured gtPrice
// {
// uint amount = msg.value / price;
// tokenContract.transferFrom(seller, msg.sender, amount);
// }
// buy with ref
function buy(address ref) external payable isConfigured gtPrice
{
if(tokenContract.balanceOf(ref) > 0) {
// reward referral token
tokenContract.transferFrom(seller, ref, 1);
}
uint amount = msg.value / price;
tokenContract.transferFrom(seller, tx.origin, amount);
}
function transferTo(uint256 amount, address toAddr) external payable isConfigured gtPrice
{
require(tokenContract.balanceOf(msg.sender) > amount);
require(msg.value > price * amount);
tokenContract.transferFrom(msg.sender, toAddr, amount);
}
// fallback
fallback() external payable
{
revert("Not enough Ether provided.");
}
}
|
buy with ref reward referral token
|
function buy(address ref) external payable isConfigured gtPrice
{
if(tokenContract.balanceOf(ref) > 0) {
tokenContract.transferFrom(seller, ref, 1);
}
uint amount = msg.value / price;
tokenContract.transferFrom(seller, tx.origin, amount);
}
| 14,086,653 |
./full_match/4/0xF4305F1634412b1aB8C5edeeA6dC471ed219e041/sources/github/dmfcoops/Pandimensional/contract/PTCO.sol
|
Returns the license for tokens
|
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A PANDIMENSIONAL WITHIN RANGE");
return LICENSE_TEXT;
}
| 700,067 |
/*
Contract Implementing the following workflow:
• Seller and buyer agree on contract and arbiter.
• Seller stores the contract on IPFS, make a smart contract giving it a deposit of 10% and the hash of the document on IPFS
• Buyer sends the price and a 10% deposit. Before the buyer has paid, the seller can cancel the contract and get back his deposit.
• If anything works fine, the buyer confirm the recepetion, gets his deposit back, seller get the payment and deposit back.
• Anytime, the seller can lower the amount of Ether asked as a compensation for things like partial damages or delay. The buyer has to accept it.
• Either buyer or seller can start a dispute by sending message to contract.
• Parties can submit questions and supporting evidence to IPFS.
• The arbitrator can take the deposit value and split the remaining to the buyer and seller.
*/
pragma solidity ^0.4.6;
contract ArbitratedBuyDeposit {
address public buyer;
address public seller;
address public arbitrator;
uint256 public deposit; // Deposit for each party is 1/10 the price
uint256 public pendingReturnBuyer;
uint256 public pendingReturnSeller;
uint256 public sellerProposedValue; // Value to be given to the seller. Seller can lower it. Buyer can accept it.
bool public settled;
bool public disputed;
event DocumentSubmitted(address submiter,string hashDocumentIPFS);
modifier notSettled() {if (settled) throw; _;}
modifier onlyBy(address _account) { if (msg.sender != _account) throw; _;}
/** Create the contract and put the amount needed in it.
* @param _arbitrator Party who will be able to arbitrate the contract.
* @param hashContractIPFS IPFS address of the contract.
*/
function ArbitratedBuyDeposit(address _arbitrator, string hashContractIPFS) payable {
seller=msg.sender;
arbitrator=_arbitrator;
deposit = msg.value;
DocumentSubmitted(seller,hashContractIPFS);
sellerProposedValue = 11 * deposit;
}
/** Pay the product and a 10% deposit */
function pay() payable {
if (msg.value!=deposit * 11 || buyer!=0) // Verify the price is right and it hasn't been paid yet.
throw;
buyer=msg.sender;
}
/** Confirm the reception: Give the deposit back to the buyer, allow seller to get the remaining funds.
* Note that it is necessary even with confirmImperfectReception because this function makes sure the buyer is always able to at least get his deposit back (unless settled by the arbitrator).
*/
function confirmPerfectReception() onlyBy(buyer) notSettled {
pendingReturnSeller=this.balance-deposit;
settled=true;
if (!buyer.send(deposit))
throw;
}
/** Cancel the sell offer, can only be done before it is paid. */
function cancelSellOffer() onlyBy(seller) {
if (buyer!=0) // Not possible if there is a buyer
throw;
if (!seller.send(this.balance))
throw;
}
/** Change the proposed amount to be given.
* Can only be called by the seller.
* This is used by the seller to refund some value to the buyer in case of delay or partial damage.
* @param _sellerProposedValue The value the seller is asking.
*/
function changeSellerProposedValue(uint256 _sellerProposedValue) onlyBy(seller) {
sellerProposedValue=_sellerProposedValue;
}
/** Confirm the reception and agree to pay valueToSeller, the buyer gets the remaining Ether.
* @param valueToSeller Value to be given to the seller. Must match sellerProposedValue.
*/
function confirmImperfectReception(uint256 valueToSeller) onlyBy(buyer) notSettled {
if (valueToSeller>this.balance) // You can't give more than what there is in the contract
throw;
if (valueToSeller!=sellerProposedValue) // buyer must agree with the seller for this function to be called
throw;
settled=true;
pendingReturnSeller=valueToSeller;
if (!buyer.send(this.balance-valueToSeller))
throw;
}
/** Withdraw pending return. */
function withdraw(){
uint256 amountToBeSend;
if (msg.sender==buyer){
amountToBeSend=pendingReturnBuyer;
pendingReturnBuyer=0;
}else if (msg.sender==seller){
amountToBeSend=pendingReturnSeller;
pendingReturnSeller=0;
}
else
throw;
if(!msg.sender.send(amountToBeSend))
throw;
}
/** Create a dispute, this allows the arbiter to decide how funds are splitted and get the deposit of the loosing party */
function createDispute() {
if (msg.sender!=buyer && msg.sender!=seller)
throw;
disputed=true;
}
/** The arbitrator can decide to split the funds on the contract.
* @param buyerShare The amount to be awarded to the buyer.
* @param sellerShare The amount to be awarded to the seller.
* @param hashDecisionIPFS IPFS address of decision motives.
*/
function decideSplit(uint256 buyerShare,uint256 sellerShare, string hashDecisionIPFS) onlyBy(arbitrator) notSettled {
if (!disputed)
throw;
if (buyerShare+sellerShare!=this.balance-deposit) // Verify that all the ether (except a deposit) are splitted
throw;
pendingReturnBuyer=buyerShare;
pendingReturnSeller=sellerShare;
settled=true;
DocumentSubmitted(arbitrator,hashDecisionIPFS);
if(!arbitrator.send(deposit)) // Give a deposit to the arbitrator
throw;
}
/** Submit documents relative to the dispute.
* Note that anyone can submit them, this allows third parties to give supporting documents.
* @param hashDocumentIPFS IPFS address of the document.
*/
function submit(string hashDocumentIPFS){
DocumentSubmitted(msg.sender,hashDocumentIPFS);
}
function getBalance() returns (uint256) {return this.balance;}
}
|
Cancel the sell offer, can only be done before it is paid. /
|
function cancelSellOffer() onlyBy(seller) {
throw;
if (!seller.send(this.balance))
throw;
}
| 1,846,266 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./libraries/IERC20.sol";
import "./libraries/FullMath.sol";
import "./MinterReceiver.sol";
/// @title HEX Share Market
/// @author Sam Presnal - Staker
/// @dev Sell shares priced at the original purchase rate
/// plus the applied premium
contract ShareMarket is MinterReceiver {
IERC20 public immutable hexContract;
address public immutable minterContract;
/// @dev Share price is sharesBalance/heartsBalance
/// Both balances reduce on buyShares to maintain the price,
/// keep track of hearts owed to supplier, and determine
/// when the listing is no longer buyable
struct ShareListing {
uint72 sharesBalance;
uint72 heartsBalance;
}
mapping(uint40 => ShareListing) public shareListings;
/// @dev The values are initialized onSharesMinted and
/// onEarningsMinted respectively. Used to calculate personal
/// earnings for a listing sharesOwned/sharesTotal*heartsEarned
struct ShareEarnings {
uint72 sharesTotal;
uint72 heartsEarned;
}
mapping(uint40 => ShareEarnings) public shareEarnings;
/// @notice Maintains which addresses own shares of particular stakes
/// @dev heartsOwed is only set for the supplier to keep track of
/// repayment for creating the stake
struct ListingOwnership {
uint72 sharesOwned;
uint72 heartsOwed;
bool isSupplier;
}
//keccak(stakeId, address) => ListingOwnership
mapping(bytes32 => ListingOwnership) internal shareOwners;
struct ShareOrder {
uint40 stakeId;
uint256 sharesPurchased;
address shareReceiver;
}
event AddListing(
uint40 indexed stakeId,
address indexed supplier,
uint256 data0 //shares | hearts << 72
);
event AddEarnings(uint40 indexed stakeId, uint256 heartsEarned);
event BuyShares(
uint40 indexed stakeId,
address indexed owner,
uint256 data0, //sharesPurchased | sharesOwned << 72
uint256 data1 //sharesBalance | heartsBalance << 72
);
event ClaimEarnings(uint40 indexed stakeId, address indexed claimer, uint256 heartsClaimed);
event SupplierWithdraw(uint40 indexed stakeId, address indexed supplier, uint256 heartsWithdrawn);
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, "LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
constructor(IERC20 _hex, address _minter) {
hexContract = _hex;
minterContract = _minter;
}
/// @inheritdoc MinterReceiver
function onSharesMinted(
uint40 stakeId,
address supplier,
uint72 stakedHearts,
uint72 stakeShares
) external override {
require(msg.sender == minterContract, "CALLER_NOT_MINTER");
//Seed pool with shares and hearts determining the rate
shareListings[stakeId] = ShareListing(stakeShares, stakedHearts);
//Store total shares to calculate user earnings for claiming
shareEarnings[stakeId].sharesTotal = stakeShares;
//Store how many hearts the supplier needs to be paid back
shareOwners[_hash(stakeId, supplier)] = ListingOwnership(0, stakedHearts, true);
emit AddListing(stakeId, supplier, uint256(uint72(stakeShares)) | (uint256(uint72(stakedHearts)) << 72));
}
/// @inheritdoc MinterReceiver
function onEarningsMinted(uint40 stakeId, uint72 heartsEarned) external override {
require(msg.sender == minterContract, "CALLER_NOT_MINTER");
//Hearts earned and total shares now stored in earnings
//for payout calculations
shareEarnings[stakeId].heartsEarned = heartsEarned;
emit AddEarnings(stakeId, heartsEarned);
}
/// @return Supplier hearts payable resulting from user purchases
function supplierHeartsPayable(uint40 stakeId, address supplier) external view returns (uint256) {
uint256 heartsOwed = shareOwners[_hash(stakeId, supplier)].heartsOwed;
if (heartsOwed == 0) return 0;
(uint256 heartsBalance, ) = listingBalances(stakeId);
return heartsOwed - heartsBalance;
}
/// @dev Used to calculate share price
/// @return hearts Balance of hearts remaining in the listing to be input
/// @return shares Balance of shares reamining in the listing to be sold
function listingBalances(uint40 stakeId) public view returns (uint256 hearts, uint256 shares) {
ShareListing memory listing = shareListings[stakeId];
hearts = listing.heartsBalance;
shares = listing.sharesBalance;
}
/// @dev Used to calculate personal earnings
/// @return heartsEarned Total hearts earned by the stake
/// @return sharesTotal Total shares originally on the market
function listingEarnings(uint40 stakeId) public view returns (uint256 heartsEarned, uint256 sharesTotal) {
ShareEarnings memory earnings = shareEarnings[stakeId];
heartsEarned = earnings.heartsEarned;
sharesTotal = earnings.sharesTotal;
}
/// @dev Shares owned is set to 0 when a user claims earnings
/// @return Current shares owned of a particular listing
function sharesOwned(uint40 stakeId, address owner) public view returns (uint256) {
return shareOwners[_hash(stakeId, owner)].sharesOwned;
}
/// @dev Hash together stakeId and address to form a key for
/// storage access
/// @return Listing address storage key
function _hash(uint40 stakeId, address addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(stakeId, addr));
}
/// @notice Allows user to purchase shares from multiple listings
/// @dev Lumps owed HEX into single transfer
function multiBuyShares(ShareOrder[] memory orders) external lock {
uint256 totalHeartsOwed;
for (uint256 i = 0; i < orders.length; i++) {
ShareOrder memory order = orders[i];
totalHeartsOwed += _buyShares(order.stakeId, order.shareReceiver, order.sharesPurchased);
}
hexContract.transferFrom(msg.sender, address(this), totalHeartsOwed);
}
/// @notice Allows user to purchase shares from a single listing
/// @param stakeId HEX stakeId to purchase shares from
/// @param shareReceiver The receiver of the shares being purchased
/// @param sharesPurchased The number of shares to purchase
function buyShares(
uint40 stakeId,
address shareReceiver,
uint256 sharesPurchased
) external lock {
uint256 heartsOwed = _buyShares(stakeId, shareReceiver, sharesPurchased);
hexContract.transferFrom(msg.sender, address(this), heartsOwed);
}
function _buyShares(
uint40 stakeId,
address shareReceiver,
uint256 sharesPurchased
) internal returns (uint256 heartsOwed) {
require(sharesPurchased != 0, "INSUFFICIENT_SHARES_PURCHASED");
(uint256 _heartsBalance, uint256 _sharesBalance) = listingBalances(stakeId);
require(sharesPurchased <= _sharesBalance, "INSUFFICIENT_SHARES_AVAILABLE");
//mulDivRoundingUp may result in 1 extra heart cost
//any shares purchased will always cost at least 1 heart
heartsOwed = FullMath.mulDivRoundingUp(sharesPurchased, _heartsBalance, _sharesBalance);
//Reduce hearts owed to remaining hearts balance if it exceeds it
//This can happen from extra 1 heart cost
if (heartsOwed >= _heartsBalance) {
heartsOwed = _heartsBalance;
sharesPurchased = _sharesBalance;
}
//Reduce both sides of the pool to maintain price
uint256 sharesBalance = _sharesBalance - sharesPurchased;
uint256 heartsBalance = _heartsBalance - heartsOwed;
shareListings[stakeId] = ShareListing(uint72(sharesBalance), uint72(heartsBalance));
//Add shares purchased to currently owned shares if any
bytes32 shareOwner = _hash(stakeId, shareReceiver);
uint256 newSharesOwned = shareOwners[shareOwner].sharesOwned + sharesPurchased;
shareOwners[shareOwner].sharesOwned = uint72(newSharesOwned);
emit BuyShares(
stakeId,
shareReceiver,
uint256(uint72(sharesPurchased)) | (uint256(uint72(newSharesOwned)) << 72),
uint256(uint72(sharesBalance)) | (uint256(uint72(heartsBalance)) << 72)
);
}
/// @notice Withdraw earnings as a supplier
/// @param stakeId HEX stakeId to withdraw earnings from
/// @dev Combines supplier withdraw from two sources
/// 1. Hearts paid for supplied shares by market participants
/// 2. Hearts earned from staking supplied shares (buyer fee %)
/// Note: If a listing has ended, assigns all leftover shares before withdraw
function supplierWithdraw(uint40 stakeId) external lock {
//Track total withdrawable
uint256 totalHeartsOwed = 0;
bytes32 supplier = _hash(stakeId, msg.sender);
require(shareOwners[supplier].isSupplier, "NOT_SUPPLIER");
//Check to see if heartsOwed for sold shares in listing
uint256 heartsOwed = uint256(shareOwners[supplier].heartsOwed);
(uint256 heartsBalance, uint256 sharesBalance) = listingBalances(stakeId);
//The delta between heartsOwed and heartsBalance is created
//by users buying shares from the pool and reducing heartsBalance
if (heartsOwed > heartsBalance) {
//Withdraw any hearts for shares sold
uint256 heartsPayable = heartsOwed - heartsBalance;
uint256 newHeartsOwed = heartsOwed - heartsPayable;
//Update hearts owed
shareOwners[supplier].heartsOwed = uint72(newHeartsOwed);
totalHeartsOwed = heartsPayable;
}
//Claim earnings including unsold shares only if the
//earnings have already been minted
(uint256 heartsEarned, ) = listingEarnings(stakeId);
if (heartsEarned != 0) {
uint256 supplierShares = shareOwners[supplier].sharesOwned;
//Check for unsold market shares
if (sharesBalance != 0) {
//Add unsold shares to supplier shares
supplierShares += sharesBalance;
//Update storage to reflect new shares
shareOwners[supplier].sharesOwned = uint72(supplierShares);
//Close buying from share listing
delete shareListings[stakeId];
//Remove supplier hearts owed
shareOwners[supplier].heartsOwed = 0;
emit BuyShares(
stakeId,
msg.sender,
uint256(uint72(sharesBalance)) | (uint256(supplierShares) << 72),
0
);
}
//Ensure supplier has shares (claim reverts otherwise)
if (supplierShares != 0) totalHeartsOwed += _claimEarnings(stakeId);
}
require(totalHeartsOwed != 0, "NO_HEARTS_OWED");
hexContract.transfer(msg.sender, totalHeartsOwed);
emit SupplierWithdraw(stakeId, msg.sender, totalHeartsOwed);
}
/// @notice Withdraw earnings as a market participant
/// @param stakeId HEX stakeId to withdraw earnings from
function claimEarnings(uint40 stakeId) external lock {
uint256 heartsEarned = _claimEarnings(stakeId);
require(heartsEarned != 0, "NO_HEARTS_EARNED");
hexContract.transfer(msg.sender, heartsEarned);
}
function _claimEarnings(uint40 stakeId) internal returns (uint256 heartsOwed) {
(uint256 heartsEarned, uint256 sharesTotal) = listingEarnings(stakeId);
require(sharesTotal != 0, "LISTING_NOT_FOUND");
require(heartsEarned != 0, "SHARES_NOT_MATURE");
bytes32 owner = _hash(stakeId, msg.sender);
uint256 ownedShares = shareOwners[owner].sharesOwned;
require(ownedShares != 0, "NO_SHARES_OWNED");
heartsOwed = FullMath.mulDiv(heartsEarned, ownedShares, sharesTotal);
shareOwners[owner].sharesOwned = 0;
emit ClaimEarnings(stakeId, msg.sender, heartsOwed);
}
}
// 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: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./libraries/ERC165.sol";
/// @title HEX Minter Receiver
/// @author Sam Presnal - Staker
/// @dev Receives shares and hearts earned from the ShareMinter
abstract contract MinterReceiver is ERC165 {
/// @notice ERC165 ensures the minter receiver supports the interface
/// @param interfaceId The MinterReceiver interface id
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(MinterReceiver).interfaceId || super.supportsInterface(interfaceId);
}
/// @notice Receives newly started stake properties
/// @param stakeId The HEX stakeId
/// @param supplier The reimbursement address for the supplier
/// @param stakedHearts Hearts staked
/// @param stakeShares Shares available
function onSharesMinted(
uint40 stakeId,
address supplier,
uint72 stakedHearts,
uint72 stakeShares
) external virtual;
/// @notice Receives newly ended stake properties
/// @param stakeId The HEX stakeId
/// @param heartsEarned Hearts earned from the stake
function onEarningsMinted(uint40 stakeId, uint72 heartsEarned) external virtual;
}
// 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 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);
}
|
Withdraw earnings as a supplier stakeId HEX stakeId to withdraw earnings from Combines supplier withdraw from two sources 1. Hearts paid for supplied shares by market participants 2. Hearts earned from staking supplied shares (buyer fee %) Note: If a listing has ended, assigns all leftover shares before withdrawTrack total withdrawableCheck to see if heartsOwed for sold shares in listingThe delta between heartsOwed and heartsBalance is createdby users buying shares from the pool and reducing heartsBalanceWithdraw any hearts for shares soldUpdate hearts owedCheck for unsold market sharesAdd unsold shares to supplier sharesUpdate storage to reflect new sharesClose buying from share listingRemove supplier hearts owed
|
function supplierWithdraw(uint40 stakeId) external lock {
uint256 totalHeartsOwed = 0;
bytes32 supplier = _hash(stakeId, msg.sender);
require(shareOwners[supplier].isSupplier, "NOT_SUPPLIER");
uint256 heartsOwed = uint256(shareOwners[supplier].heartsOwed);
(uint256 heartsBalance, uint256 sharesBalance) = listingBalances(stakeId);
if (heartsOwed > heartsBalance) {
uint256 heartsPayable = heartsOwed - heartsBalance;
uint256 newHeartsOwed = heartsOwed - heartsPayable;
shareOwners[supplier].heartsOwed = uint72(newHeartsOwed);
totalHeartsOwed = heartsPayable;
}
if (heartsEarned != 0) {
uint256 supplierShares = shareOwners[supplier].sharesOwned;
if (sharesBalance != 0) {
supplierShares += sharesBalance;
shareOwners[supplier].sharesOwned = uint72(supplierShares);
delete shareListings[stakeId];
shareOwners[supplier].heartsOwed = 0;
emit BuyShares(
stakeId,
msg.sender,
uint256(uint72(sharesBalance)) | (uint256(supplierShares) << 72),
0
);
}
}
require(totalHeartsOwed != 0, "NO_HEARTS_OWED");
hexContract.transfer(msg.sender, totalHeartsOwed);
emit SupplierWithdraw(stakeId, msg.sender, totalHeartsOwed);
}
| 13,965,041 |
./full_match/80001/0x44f96b2b565dDd8e690C68CE795eA14dee1cF81c/sources/contracts/NFTAttack.sol
|
can only transfer weapon transfering level 1 NFT gives you a level 2 NFT
|
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public override gameNotPaused {
require(id == 0, "This weapon is not transferable!");
super.safeTransferFrom(from, to, id, amount, data);
if(from != to && id == 0) {
_mint(from, 1, 1, "");
}
}
| 5,631,270 |
// 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;
/**
* @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.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'
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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// 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);
}
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;
/*
* @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;
// 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.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract FixedStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// user deposits are recorded in StakeInfo[] stakes struct
struct StakeInfo {
// staked is true if deposit is staked and hasn't been unstaked.
// After user claims his stake back, `staked` becomes false
bool staked;
// stakedAmount get recorded at the stake time and doesn't change.
uint256 stakedAmount;
uint256 startTime;
// endTime and totalYield get calculated in advance at the moment of staking
// endTime is the date when unstaking becomes possible (without penalties)
uint256 endTime;
// totalYield is a total value of rewards for the given stake.
// Gets calculated on the stake start and doesnt' change
// but the amount that user is able to withdraw gets gradually unlocked over time.
uint256 totalYield;
// The amount of yield user already harvested and the time of last harvest call.
uint256 harvestedYield;
uint256 lastHarvestTime;
}
// If stakesOpen == true, the contract is operational and accepts new stakes.
// Otherwise it allows just harvesting and unstaking.
bool public stakesOpen;
// The token accepted for staking and used for rewards (The same token for both).
IERC20 public token;
// struccture that stores the records of users' stakes
mapping(address => StakeInfo[]) public stakes;
// the total number of staked tokens. Accounted separately to avoid mixing stake and reward balances
uint256 public stakedTokens;
// The staking interval in days.
// Early unstaking is possible but a fine is withheld.
uint256 public stakeDurationDays;
// Fee for early unstake in basis points (1/10000)
// If the user withdraws before stake expiration, he pays `earlyUnstakeFee`
uint256 public earlyUnstakeFee;
// Reward that staker will receive for his stake
// nominated in basis points (1/10000) of staked amount
uint256 public yieldRate;
// Yield tokens reserved for existing stakes to pay on harvest.
// The reward tokens get allocated at the moment of stake.
uint256 public allocatedTokens;
// unallocated (excess) tokens can be withdrawn by the contract owner not earlier than 18 months
uint256 public constant WITHDRAWAL_LOCKUP_DURATION = 30 days * 18;
uint256 public withdrawalUnlockTime;
event Stake(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 startTime, uint256 endTime);
event Unstake(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 startTime, uint256 endTime, bool early);
event Harvest(address indexed user, uint256 indexed stakeId, uint256 amount, uint256 harvestTime);
/**
* @dev the constructor arguments:
* @param _token address of token - the same accepted for staking and used to pay rewards
* @param _stakeDurationDays the stake duration in days
* @param _yieldRate reward rate in basis points (1/10000)
* @param _earlyUnstakeFee fee for unstaking before stake expiration
*/
constructor(
address _token,
uint256 _stakeDurationDays,
uint256 _yieldRate,
uint256 _earlyUnstakeFee
) {
require(_token != address(0), "Empty token address");
require(_yieldRate > 0, "Zero yield rate");
require(_earlyUnstakeFee > 0, "Zero early Unstake Fee");
token = IERC20(_token);
stakeDurationDays = _stakeDurationDays;
yieldRate = _yieldRate;
earlyUnstakeFee = _earlyUnstakeFee;
withdrawalUnlockTime = _now().add(WITHDRAWAL_LOCKUP_DURATION);
}
/**
* @dev the owner is able to withdraw excess tokens to collect early unstake fees or to reuse unused funds
* suitable for assets rebalancing between staking contracts.
* @param _to address who will receive the funds
* @param _amount amount of tokens in atto (1e-18) units
*/
function withdrawUnallocatedTokens(address _to, uint256 _amount) public onlyOwner {
require(_to != address(0), "Empty receiver address");
require(_amount > 0, "Zero amount");
require(unallocatedTokens() >= _amount, "Not enough unallocatedTokens");
require(_now() >= withdrawalUnlockTime, "Can't withdraw until withdrawalUnlockTime");
token.safeTransfer(_to, _amount);
}
/**
* @dev start accepting new stakes. Called only by the owner
*/
function start() public onlyOwner {
require(!stakesOpen, "Stakes are open already");
stakesOpen = true;
}
/**
* @dev stop accepting new stakes. Called only by the owner
*/
function stop() public onlyOwner {
require(stakesOpen, "Stakes are stopped already");
stakesOpen = false;
}
/**
* @dev submit the stake
* @param _amount amount of tokens to be transferred from user's account
*/
function stake(uint256 _amount) external {
require(stakesOpen, "stake: not open");
require(_amount > 0, "stake: zero amount");
// entire reward allocated for the user for this stake
uint256 totalYield = _amount.mul(yieldRate).div(10000);
require(unallocatedTokens() >= totalYield, "stake: not enough allotted tokens to pay yield");
uint256 startTime = _now();
uint256 endTime = _now().add(stakeDurationDays.mul(1 days));
stakes[msg.sender].push(
StakeInfo({
staked: true,
stakedAmount: _amount,
startTime: startTime,
endTime: endTime,
totalYield: totalYield,
harvestedYield: 0,
lastHarvestTime: startTime
})
);
allocatedTokens = allocatedTokens.add(totalYield);
stakedTokens = stakedTokens.add(_amount);
uint256 stakeId = getStakesLength(msg.sender).sub(1);
emit Stake(msg.sender, stakeId, _amount, startTime, endTime);
token.safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @dev withdraw the `body` of user's stake. Can be called only once
* @param _stakeId Id of the stake
*/
function unstake(uint256 _stakeId) external {
(
bool staked,
uint256 stakedAmount,
uint256 startTime,
uint256 endTime,
uint256 totalYield,
uint256 harvestedYield,
,
uint256 harvestableYield
) = getStake(msg.sender, _stakeId);
bool early;
require(staked, "Unstaked already");
if (_now() > endTime) {
stakes[msg.sender][_stakeId].staked = false;
stakedTokens = stakedTokens.sub(stakedAmount);
early = false;
token.safeTransfer(msg.sender, stakedAmount);
} else {
uint256 newTotalYield = harvestedYield.add(harvestableYield);
allocatedTokens = allocatedTokens.sub(totalYield.sub(newTotalYield));
stakes[msg.sender][_stakeId].staked = false;
stakes[msg.sender][_stakeId].endTime = _now();
stakes[msg.sender][_stakeId].totalYield = newTotalYield;
stakedTokens = stakedTokens.sub(stakedAmount);
early = true;
uint256 fee = stakedAmount.mul(earlyUnstakeFee).div(10000);
uint256 amountToTransfer = stakedAmount.sub(fee);
token.safeTransfer(msg.sender, amountToTransfer);
}
emit Unstake(msg.sender, _stakeId, stakedAmount, startTime, endTime, early);
}
/**
* @dev harvest accumulated rewards. Can be called many times.
* @param _stakeId Id of the stake
*/
function harvest(uint256 _stakeId) external {
(, , , , , uint256 harvestedYield, , uint256 harvestableYield) = getStake(msg.sender, _stakeId);
require(harvestableYield != 0, "harvestableYield is zero");
allocatedTokens = allocatedTokens.sub(harvestableYield);
stakes[msg.sender][_stakeId].harvestedYield = harvestedYield.add(harvestableYield);
stakes[msg.sender][_stakeId].lastHarvestTime = _now();
emit Harvest(msg.sender, _stakeId, harvestableYield, _now());
token.safeTransfer(msg.sender, harvestableYield);
}
/**
* @dev get the amount of available tokens neither staked nor allocated for rewards
* @return amount of unallocated tokens
*/
function unallocatedTokens() public view returns (uint256) {
return token.balanceOf(address(this)).sub(stakedTokens).sub(allocatedTokens);
}
/**
* @dev get the count of user's stakes. Used on frontend to iterate and display individual stakes
* @param _userAddress account of staker
* @return stakes
*/
function getStakesLength(address _userAddress) public view returns (uint256) {
return stakes[_userAddress].length;
}
/**
* @dev get the individual stake parameters of the user
* @param _userAddress account of staker
* @param _stakeId stake index
* @return staked the status of stake
* @return stakedAmount the number of deposited tokens
* @return startTime the moment of stake start
* @return endTime the time when unstaking (w.o. penalties) becomes possible
* @return totalYield entire yield for the stake (totally released on endTime)
* @return harvestedYield The part of yield user harvested already
* @return lastHarvestTime The time of last harvest event
* @return harvestableYield The unlocked part of yield available for harvesting
*/
function getStake(address _userAddress, uint256 _stakeId)
public
view
returns (
bool staked,
uint256 stakedAmount,
uint256 startTime,
uint256 endTime,
uint256 totalYield, // Entire yield for the stake (totally released on endTime)
uint256 harvestedYield, // The part of yield user harvested already
uint256 lastHarvestTime, // The time of last harvest event
uint256 harvestableYield // The unlocked part of yield available for harvesting
)
{
StakeInfo memory _stake = stakes[_userAddress][_stakeId];
staked = _stake.staked;
stakedAmount = _stake.stakedAmount;
startTime = _stake.startTime;
endTime = _stake.endTime;
totalYield = _stake.totalYield;
harvestedYield = _stake.harvestedYield;
lastHarvestTime = _stake.lastHarvestTime;
if (_now() > endTime) {
harvestableYield = totalYield.sub(harvestedYield);
} else {
harvestableYield = totalYield.mul(_now().sub(lastHarvestTime)).div(endTime.sub(startTime));
}
}
// Returns block.timestamp, overridable for test purposes.
function _now() internal view virtual returns (uint256) {
return block.timestamp;
}
}
|
submit the stake _amount amount of tokens to be transferred from user's account/ entire reward allocated for the user for this stake
|
function stake(uint256 _amount) external {
require(stakesOpen, "stake: not open");
require(_amount > 0, "stake: zero amount");
uint256 totalYield = _amount.mul(yieldRate).div(10000);
require(unallocatedTokens() >= totalYield, "stake: not enough allotted tokens to pay yield");
uint256 startTime = _now();
uint256 endTime = _now().add(stakeDurationDays.mul(1 days));
stakes[msg.sender].push(
StakeInfo({
staked: true,
stakedAmount: _amount,
startTime: startTime,
endTime: endTime,
totalYield: totalYield,
harvestedYield: 0,
lastHarvestTime: startTime
})
);
allocatedTokens = allocatedTokens.add(totalYield);
stakedTokens = stakedTokens.add(_amount);
uint256 stakeId = getStakesLength(msg.sender).sub(1);
emit Stake(msg.sender, stakeId, _amount, startTime, endTime);
token.safeTransferFrom(msg.sender, address(this), _amount);
}
| 1,735,189 |
/**
*Submitted for verification at Etherscan.io on 2022-04-18
*/
// File: @openzeppelin/contracts/utils/Strings.sol
// 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/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/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/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.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
* ====
*
* [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.
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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.
return account.code.length > 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: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/token/ERC721/IERC721.sol
// 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/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @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: erc721a/contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
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;
// 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;
// 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();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @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 = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
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) internal {
_safeMint(to, quantity, '');
}
/**
* @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
) internal {
_mint(to, quantity, _data, 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,
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);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
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 {}
/**
* @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: PoopDoggies.sol
pragma solidity ^0.8.7;
contract PoopDoggies is ERC721A, Ownable {
uint256 public MAX_MINTS = 3;
uint256 MAX_SUPPLY_DEV = 2000;
uint256 public MAX_SUPPLY = 2000;
uint256 public mintRate = 0.0025 ether;
bool public saleIsActive = true;
string public baseURI = "https://gateway.pinata.cloud/ipfs/QmUE72js1yv5ggPMppXJF9FjKeHuN6X8Gfv9Qy9jto2awA/";
constructor(string memory _name, string memory _symbol) ERC721A(_name, _symbol) {}
function mint(uint256 quantity) external payable {
// _safeMint's second argument now takes in a quantity, not a tokenId.
require(saleIsActive, "Sale must be active to mint");
require(quantity <= MAX_MINTS, "Exceeded the limit");
require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough tokens left");
require(msg.value >= (mintRate * quantity), "Not enough ether sent");
_safeMint(msg.sender, quantity);
}
function reserveMint(uint256 quantity) public onlyOwner {
require(quantity <= MAX_SUPPLY_DEV, "Not enough tokens left");
_safeMint(msg.sender, quantity);
}
function flipSaleStatus() public onlyOwner {
saleIsActive = !saleIsActive;
}
function setCost(uint256 _cost) public onlyOwner {
mintRate = _cost;
}
function withdraw() external payable onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json")) : "";
}
}
|
_safeMint's second argument now takes in a quantity, not a tokenId.
|
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.7;
function mint(uint256 quantity) external payable {
require(saleIsActive, "Sale must be active to mint");
require(quantity <= MAX_MINTS, "Exceeded the limit");
require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough tokens left");
require(msg.value >= (mintRate * quantity), "Not enough ether sent");
_safeMint(msg.sender, quantity);
}
| 2,246,558 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/*import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.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 ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @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;
}
}
// 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);
}
}
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;
}
}
contract MintNft is ERC721, Ownable, ReentrancyGuard{
using Counters for Counters.Counter;
Counters.Counter _tokenIdTracker;
mapping(uint256 => string) public _tokenURIs; //returns uris for particular token id
mapping(uint256 => address) public minter; //returs minter of a token id
mapping(uint256 => uint256) public royalty; //returns royalty of a token id
mapping(address => uint256[]) public mintedByUser;
uint256 public maximumRoyalty = 100;
constructor(string memory NAME, string memory SYMBOL) ERC721(NAME,SYMBOL) {
}
event minted (uint256 _NftId, string msg);
event BatchMint(uint256 _totalNft, string msg);
function _mintNft(address creator, string memory _TokenURI, uint256 _royaltyPercentage)
internal
returns (uint256)
{
uint256 NftId = _tokenIdTracker.current();
_safeMint(creator, NftId);
mintedByUser[creator].push(NftId);
royalty[NftId] = _royaltyPercentage;
minter[NftId] = creator;
_setTokenURI(NftId,_TokenURI);
_tokenIdTracker.increment();
emit minted (NftId,"succesfully minted");
return (NftId);
}
// function to mint multiple nfts
function batchMint( string[] memory _uri, uint256[] memory _royalty) external nonReentrant returns (bool) {
require(_uri.length == _royalty.length,"Length of Uri and Royalty should be same");
uint256 _totalNft = _uri.length;
for(uint i = 0; i< _totalNft; i++) {
require(_royalty[i]< maximumRoyalty,"Royalty cannnot be 100 or more");
_mintNft(msg.sender, _uri[i], _royalty[i]);
}
emit BatchMint(_totalNft, "Batch Mint Success");
return true;
}
// returns royalty
function royaltyForToken(uint256 tokenId) external view isValidId(tokenId) returns (uint256 percentage){
return(royalty[tokenId]);
}
// returns minter of a token
function minterOfToken(uint256 tokenId) external view returns (address _minter){
return(minter[tokenId]);
}
// sets uri for a token
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal isValidId(tokenId)
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
// returns the total amount of NFTs minted
function getTokenCounter() external view returns (uint256 tracker){
return(_tokenIdTracker.current());
}
function setMaxRoyalty(uint256 _royalty) external onlyOwner{
maximumRoyalty = _royalty;
}
function getNFTMintedByUser(address user) external view returns (uint256[] memory ids){
return(mintedByUser[user]);
}
// returns uri of a particular token
function tokenURI(uint256 tokenId)
public
view
override isValidId(tokenId)
returns (string memory)
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
// update uri of a token
function UpdateTokenURI(uint256 tokenId, string memory _TokenURI)
external isValidId(tokenId)
{ require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
require(
ownerOf(tokenId) == msg.sender,
"NFT_Minter: Only Owner Can update a NFT"
);
_setTokenURI(tokenId,_TokenURI);
}
// modifier to check id tokenid exists or not
modifier isValidId( uint256 nftId){
require(nftId <= _tokenIdTracker.current());
_;
}
}
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;
}
}
}
contract OpenToBids is IERC721Receiver, ReentrancyGuard, Ownable{
using Counters for Counters.Counter;
using SafeMath for uint;
Counters.Counter private _itemIds; //count of sale items
Counters.Counter private _itemsSold; //count of sold items
Counters.Counter private _itemsinActive;
address payable treasury; // to transfer listingPrice
address payable _seller;
address payable _minter;
MintNft public pangeaNft;
address pangeaNftAddress;
uint256 public treasuryRoyalty = 3;
constructor(address _nftContract,address _treasury) {
pangeaNftAddress = _nftContract; //nft contract for pangea platform
pangeaNft = MintNft(_nftContract);
treasury = payable(_treasury);
}
struct MarketItem {
uint itemId;
address nftContract;
uint256 tokenId;
address payable seller;
address payable minter;
address payable highestBidder;
uint256 royalty;
uint256 highestBid;
bool sold;
bool isActive;
}
mapping(uint256 => MarketItem) public idToMarketItem;
event saleCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address seller,
address minter,
address highestBidder,
uint256 royalty,
uint256 highestBid,
bool sold,
bool isActive
);
event ItemBought(
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address buyer,
uint256 highestBid,
bool sold,
bool isActive
);
function setTreasuryRoyalty(uint256 royalty) external onlyOwner {
treasuryRoyalty = royalty;
}
function setTreasury(address _treasury) external onlyOwner {
treasury = payable(_treasury);
}
function getHighestBid(uint256 itemid) external view returns (uint256) {
return idToMarketItem[itemid].highestBid;
}
function getHighestBidder(uint256 itemid) external view returns (address payable) {
return idToMarketItem[itemid].highestBidder;
}
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function createSale(
address nftContract,
uint256 tokenId
) external nonReentrant {
require(nftContract!=address(0),"zero address cannot be an input");
address tokenOwner = IERC721(nftContract).ownerOf(tokenId);
require(msg.sender == IERC721(nftContract).getApproved(tokenId) || msg.sender == tokenOwner,
"Caller must be approved or owner for token id");
address minter = address(0);
uint256 royalty = 0;
_itemIds.increment();
uint256 itemId = _itemIds.current();
if( nftContract == pangeaNftAddress){
minter = pangeaNft.minterOfToken(tokenId);
royalty = pangeaNft.royaltyForToken(tokenId);
}
idToMarketItem[itemId] = MarketItem(
itemId,
nftContract,
tokenId,
payable(msg.sender),
payable(minter),
payable(address(0)),
royalty,
0,
false,
true
);
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenId); //nft gets transferred to the contract
emit saleCreated(
itemId,
nftContract,
tokenId,
msg.sender,
minter,
address(0),
royalty,
0,
false,
true
);
}
function bidOnItem(
uint256 itemId
) external payable nonReentrant {
require(itemId <= _itemIds.current(), " Enter a valid Id");
require( idToMarketItem[itemId].isActive==true,"the sale is not active");
require(msg.sender!= idToMarketItem[itemId].seller,"seller cannot buy");
// uint tokenId = idToMarketItem[itemId].tokenId;
require(msg.value > idToMarketItem[itemId].highestBid, "Bid should be higher than the highest bid.");
require( idToMarketItem[itemId].sold == false,"Already Sold");
idToMarketItem[itemId].highestBid = msg.value;
idToMarketItem[itemId].highestBidder = payable(msg.sender);
}
function sellItem(uint256 itemId) external nonReentrant{
require(itemId <= _itemIds.current(), " Enter a valid Id");
require(msg.sender==idToMarketItem[itemId].seller && idToMarketItem[itemId].sold == false && idToMarketItem[itemId].isActive == true );
uint tokenId = idToMarketItem[itemId].tokenId;
_seller = idToMarketItem[itemId].seller;
_minter = idToMarketItem[itemId].minter;
uint256 royalty = idToMarketItem[itemId].royalty;
uint value = idToMarketItem[itemId].highestBid;
if(royalty !=0){
uint256 amountToadmin = ((value).mul((treasuryRoyalty))).div(100) ;
uint256 remainingAmount = (value).sub(amountToadmin);
uint256 amountTominter = ((remainingAmount).mul((royalty))).div(100) ;
uint256 amountToSeller = (remainingAmount).sub(amountTominter);
payable(_minter).transfer(amountTominter);
payable(treasury).transfer(amountToadmin);
payable(_seller).transfer(amountToSeller);
}
else{
uint256 amountToadmin = ((value).mul((treasuryRoyalty))).div(100) ;
uint256 remainingAmount = (value).sub(amountToadmin);
payable(treasury).transfer(amountToadmin);
payable(_seller).transfer(remainingAmount);
}
IERC721(idToMarketItem[itemId].nftContract).approve(0x0000000000000000000000000000000000000000,idToMarketItem[itemId].tokenId);
IERC721(idToMarketItem[itemId].nftContract).safeTransferFrom(address(this), idToMarketItem[itemId].highestBidder, tokenId);
// idToMarketItem[itemId].owner = payable(idToMarketItem[itemId].highestBidder);
idToMarketItem[itemId].sold = true;
idToMarketItem[itemId].isActive = false;
_itemsSold.increment();
_itemsinActive.increment();
emit ItemBought(
itemId,
idToMarketItem[itemId].nftContract,
tokenId,
idToMarketItem[itemId].highestBidder,
idToMarketItem[itemId].highestBid,
true,
false
);
}
function EndSale(uint256 itemId) external nonReentrant {
require(itemId <= _itemIds.current(), " Enter a valid Id");
require(msg.sender==idToMarketItem[itemId].seller && idToMarketItem[itemId].sold == false && idToMarketItem[itemId].isActive == true );
idToMarketItem[itemId].isActive = false;
_itemsinActive.increment();
IERC721(idToMarketItem[itemId].nftContract).approve(0x0000000000000000000000000000000000000000,idToMarketItem[itemId].tokenId);
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
}
function royaltyForItem(uint256 item) external view returns(uint256){
require(item <= _itemIds.current(), " Enter a valid Id");
return(idToMarketItem[item].royalty);
}
/* Returns all unsold market items */
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint itemCount = _itemIds.current();
uint unsoldItemCount = _itemIds.current().sub(_itemsinActive.current());
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint i = 0; i < itemCount; i++) {
if ( idToMarketItem[i.add(1)].isActive ==true )
{
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1);
}
}
return items;
}
function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].highestBidder == msg.sender) {
itemCount = itemCount.add(1) ;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].highestBidder == msg.sender) {
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1);
}
}
return items;
}
/* Returns only items a user has created */
function fetchItemsCreated() public view returns (MarketItem[] memory) {
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].seller == msg.sender) {
itemCount = itemCount.add(1);
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i.add(1)].seller == msg.sender) {
uint currentId = i.add(1);
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex = currentIndex.add(1) ;
}
}
return items;
}
receive() external payable {}
fallback() external payable {}
}
|
sets uri for a token
|
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal isValidId(tokenId)
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
| 439,229 |
./full_match/1/0xed7B4C5597f3574355AE6E404f7d3930A1Ba62FF/sources/contracts/AtomicNFT.sol
|
Returns true if the owner as shown a trusted CK proof type/
|
function isTrustedCK(address addr) public returns (bool) {
return ckRegistry.verifications(addr).storedValue & trustedVerificationBits != 0;
}
| 16,415,331 |
pragma solidity ^0.4.24;
contract SHT_Token
{
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyTokenHolders()
{
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyDividendPositive()
{
require(myDividends() > 0);
_;
}
// only owner
modifier onlyOwner()
{
require (address(msg.sender) == owner);
_;
}
// only founders if contract not live
modifier onlyFoundersIfNotPublic()
{
if(!openToThePublic)
{
require (founders[address(msg.sender)] == true);
}
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event lotteryPayout(
address customerAddress,
uint256 lotterySupply
);
event whaleDump(
uint256 amount
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "SHT Token";
string public symbol = "SHT";
bool public openToThePublic = false;
address public owner;
address public dev;
uint8 constant public decimals = 18;
uint8 constant internal dividendFee = 10; //11% (total.. breakdown is 5% tokenholders, 2.5% OB2, 1.5% whale, 1% lottery, 1% dev)
uint8 constant internal lotteryFee = 5;
uint8 constant internal devFee = 5;
uint8 constant internal ob2Fee = 2;
uint256 constant internal tokenPrice = 400000000000000; //0.0004 ether
uint256 constant internal magnitude = 2**64;
Onigiri2 private ob2;
/*================================
= DATASETS =
================================*/
mapping(address => uint256) internal publicTokenLedger;
mapping(address => uint256) public whaleLedger;
mapping(address => int256) internal payoutsTo_;
mapping(address => bool) internal founders;
address[] lotteryPlayers;
uint256 internal lotterySupply = 0;
uint256 internal tokenSupply = 0;
uint256 internal profitPerShare_;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// no admin, but the owner of the contract is the address used for whale
owner = address(msg.sender);
dev = address(0x7e474fe5Cfb720804860215f407111183cbc2f85); //some SHT Dev
// add founders here... Founders don't get any special priveledges except being first in line at launch day
founders[0x013f3B8C9F1c4f2f28Fd9cc1E1CF3675Ae920c76] = true; //Nomo
founders[0xF57924672D6dBF0336c618fDa50E284E02715000] = true; //Bungalogic
founders[0xE4Cf94e5D30FB4406A2B139CD0e872a1C8012dEf] = true; //Ivan
// link this contract to OB2 contract to send rewards
ob2 = Onigiri2(0xb8a68f9B8363AF79dEf5c5e11B12e8A258cE5be8); //MainNet
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral address
*/
function buy()
onlyFoundersIfNotPublic()
public
payable
returns(uint256)
{
require (msg.sender == tx.origin);
uint256 tokenAmount;
tokenAmount = purchaseTokens(msg.value); //redirects to purchaseTokens so same functionality
return tokenAmount;
}
/**
* Fallback function to handle ethereum that was send straight to the contract
*/
function()
payable
public
{
buy();
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyDividendPositive()
public
{
require (msg.sender == tx.origin);
// fetch dividends
uint256 dividends = myDividends();
// pay out the dividends virtually
address customerAddress = msg.sender;
payoutsTo_[customerAddress] += int256(dividends * magnitude);
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(dividends);
// fire event for logging
emit onReinvestment(customerAddress, dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
// get token count for caller & sell them all
address customerAddress = address(msg.sender);
uint256 _tokens = publicTokenLedger[customerAddress];
if(_tokens > 0)
{
sell(_tokens);
}
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyDividendPositive()
public
{
require (msg.sender == tx.origin);
// setup data
address customerAddress = msg.sender;
uint256 dividends = myDividends();
// update dividend tracker
payoutsTo_[customerAddress] += int256(dividends * magnitude);
customerAddress.transfer(dividends);
// fire event for logging
emit onWithdraw(customerAddress, dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0));
uint256 _tokens = _amountOfTokens;
uint256 ethereum = tokensToEthereum_(_tokens);
uint256 undividedDivs = SafeMath.div(ethereum, dividendFee);
// from that 10%, divide for Community, Whale, Lottery, and OB2
uint256 communityDivs = SafeMath.div(undividedDivs, 2); //5%
uint256 ob2Divs = SafeMath.div(undividedDivs, 4); //2.5%
uint256 lotteryDivs = SafeMath.div(undividedDivs, 10); // 1%
uint256 tip4Dev = lotteryDivs;
uint256 whaleDivs = SafeMath.sub(communityDivs, (ob2Divs + lotteryDivs)); // 1.5%
// let's deduct Whale, Lottery, and OB2 divs just to make sure our math is safe
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(ethereum, (undividedDivs + tip4Dev));
//add divs to whale
whaleLedger[owner] += whaleDivs;
//add tokens to the lotterySupply
lotterySupply += ethereumToTokens_(lotteryDivs);
//send divs to OB2
ob2.fromGame.value(ob2Divs)();
//send tip to Dev
dev.transfer(tip4Dev);
// burn the sold tokens
tokenSupply -= _tokens;
publicTokenLedger[msg.sender] -= _tokens;
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply > 0)
{
// update the amount of dividends per token
profitPerShare_ += ((dividends * magnitude) / tokenSupply);
}
// fire event for logging
emit onTokenSell(msg.sender, _tokens, taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyTokenHolders()
public
returns(bool)
{
assert(_toAddress != owner);
// make sure we have the requested tokens
require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 ));
// exchange tokens
publicTokenLedger[msg.sender] -= _amountOfTokens;
publicTokenLedger[_toAddress] += _amountOfTokens;
// update dividend trackers
payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens);
// fire event for logging
emit Transfer(msg.sender, _toAddress, _amountOfTokens);
return true;
}
/*---------- OWNER ONLY FUNCTIONS ----------*/
/**
* Want to prevent snipers from buying prior to launch
*/
function goPublic()
onlyOwner()
public
returns(bool)
{
openToThePublic = true;
return openToThePublic;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return (tokenSupply + lotterySupply); //adds the tokens from ambassadors to the supply (but not to the dividends calculation which is based on the supply)
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
return balanceOf(msg.sender);
}
/**
* Retrieve the balance of the whale.
*/
function whaleBalance()
public
view
returns(uint256)
{
return whaleLedger[owner];
}
/**
* Retrieve the balance of the whale.
*/
function lotteryBalance()
public
view
returns(uint256)
{
return lotterySupply;
}
/**
* Retrieve the dividends owned by the caller.
*/
function myDividends()
public
view
returns(uint256)
{
return dividendsOf(msg.sender);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address customerAddress)
view
public
returns(uint256)
{
return publicTokenLedger[customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * publicTokenLedger[customerAddress]) - payoutsTo_[customerAddress]) / magnitude;
}
/**
* Return the buy and sell price of 1 individual token.
*/
function buyAndSellPrice()
public
pure
returns(uint256)
{
uint256 ethereum = tokenPrice;
uint256 dividends = SafeMath.div((ethereum * dividendFee ), 100);
uint256 taxedEthereum = SafeMath.sub(ethereum, dividends);
return taxedEthereum;
}
/**
* Function for the frontend to dynamically retrieve the price of buy orders.
*/
function calculateTokensReceived(uint256 ethereumToSpend)
public
pure
returns(uint256)
{
require(ethereumToSpend >= tokenPrice);
uint256 dividends = SafeMath.div((ethereumToSpend * dividendFee), 100);
uint256 taxedEthereum = SafeMath.sub(ethereumToSpend, dividends);
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
return amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price of sell orders.
*/
function calculateEthereumReceived(uint256 tokensToSell)
public
view
returns(uint256)
{
require(tokensToSell <= tokenSupply);
uint256 ethereum = tokensToEthereum_(tokensToSell);
uint256 dividends = SafeMath.div((ethereum * dividendFee ), 100);
uint256 taxedEthereum = SafeMath.sub(ethereum, dividends);
return taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 incomingEthereum)
internal
returns(uint256)
{
// take out 10% of incoming eth for divs
uint256 undividedDivs = SafeMath.div(incomingEthereum, dividendFee);
// from that 10%, divide for Community, Whale, Lottery, and OB2
uint256 communityDivs = SafeMath.div(undividedDivs, 2); //5%
uint256 ob2Divs = SafeMath.div(undividedDivs, 4); //2.5%
uint256 lotteryDivs = SafeMath.div(undividedDivs, 10); // 1%
uint256 tip4Dev = lotteryDivs;
uint256 whaleDivs = SafeMath.sub(communityDivs, (ob2Divs + lotteryDivs)); // 1.5%
// let's deduct Whale, Lottery, devfee, and OB2 divs just to make sure our math is safe
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(incomingEthereum, (undividedDivs + tip4Dev));
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
//add divs to whale
whaleLedger[owner] += whaleDivs;
//add tokens to the lotterySupply
lotterySupply += ethereumToTokens_(lotteryDivs);
//add entry to lottery
lotteryPlayers.push(msg.sender);
//send divs to OB2
ob2.fromGame.value(ob2Divs)();
//tip the dev
dev.transfer(tip4Dev);
uint256 fee = dividends * magnitude;
require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply);
uint256 payoutDividends = isWhalePaying();
// we can't give people infinite ethereum
if(tokenSupply > 0)
{
// add tokens to the pool
tokenSupply += amountOfTokens;
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply));
// calculate the amount of tokens the customer receives over his purchase
fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)));
} else
{
// add tokens to the pool
tokenSupply = amountOfTokens;
//if there are zero tokens prior to this buy, and the whale is triggered, send dividends back to whale
if(whaleLedger[owner] == 0)
{
whaleLedger[owner] = payoutDividends;
}
}
// update circulating supply & the ledger address for the customer
publicTokenLedger[msg.sender] += amountOfTokens;
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
int256 _updatedPayouts = int256((profitPerShare_ * amountOfTokens) - fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event for logging
emit onTokenPurchase(msg.sender, incomingEthereum, amountOfTokens);
return amountOfTokens;
}
/**
* Calculate token sell value.
* It's a simple algorithm. Hopefully, you don't need a whitepaper with it in scientific notation.
*/
function isWhalePaying()
private
returns(uint256)
{
uint256 payoutDividends = 0;
// this is where we check for lottery winner
if(whaleLedger[owner] >= 1 ether)
{
if(lotteryPlayers.length > 0)
{
uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length;
publicTokenLedger[lotteryPlayers[winner]] += lotterySupply;
emit lotteryPayout(lotteryPlayers[winner], lotterySupply);
tokenSupply += lotterySupply;
lotterySupply = 0;
delete lotteryPlayers;
}
//whale pays out everyone its divs
payoutDividends = whaleLedger[owner];
whaleLedger[owner] = 0;
emit whaleDump(payoutDividends);
}
return payoutDividends;
}
/**
* Calculate Token price based on an amount of incoming ethereum
*It's a simple algorithm. Hopefully, you don't need a whitepaper with it in scientific notation.
*/
function ethereumToTokens_(uint256 ethereum)
internal
pure
returns(uint256)
{
uint256 tokensReceived = ((ethereum / tokenPrice) * 1e18);
return tokensReceived;
}
/**
* Calculate token sell value.
* It's a simple algorithm. Hopefully, you don't need a whitepaper with it in scientific notation.
*/
function tokensToEthereum_(uint256 coin)
internal
pure
returns(uint256)
{
uint256 ethReceived = tokenPrice * (SafeMath.div(coin, 1e18));
return ethReceived;
}
}
contract Onigiri2
{
function fromGame() external payable;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
}
|
only people with tokens
|
{
= MODIFIERS =
=================================*/
modifier onlyTokenHolders()
{
require(myTokens() > 0);
_;
}
modifier onlyDividendPositive()
{
require(myDividends() > 0);
_;
}
modifier onlyOwner()
{
require (address(msg.sender) == owner);
_;
}
modifier onlyFoundersIfNotPublic()
{
if(!openToThePublic)
{
require (founders[address(msg.sender)] == true);
}
_;
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event lotteryPayout(
address customerAddress,
uint256 lotterySupply
);
event whaleDump(
uint256 amount
);
address indexed from,
address indexed to,
uint256 tokens
);
=====================================*/
string public name = "SHT Token";
string public symbol = "SHT";
bool public openToThePublic = false;
address public owner;
address public dev;
uint8 constant public decimals = 18;
uint8 constant internal lotteryFee = 5;
uint8 constant internal devFee = 5;
uint8 constant internal ob2Fee = 2;
uint256 constant internal magnitude = 2**64;
Onigiri2 private ob2;
================================*/
mapping(address => uint256) internal publicTokenLedger;
mapping(address => uint256) public whaleLedger;
mapping(address => int256) internal payoutsTo_;
mapping(address => bool) internal founders;
address[] lotteryPlayers;
uint256 internal lotterySupply = 0;
uint256 internal tokenSupply = 0;
uint256 internal profitPerShare_;
=======================================*/
public
{
if(!openToThePublic)
{
require (founders[address(msg.sender)] == true);
}
_;
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event lotteryPayout(
address customerAddress,
uint256 lotterySupply
);
event whaleDump(
uint256 amount
);
address indexed from,
address indexed to,
uint256 tokens
);
=====================================*/
string public name = "SHT Token";
string public symbol = "SHT";
bool public openToThePublic = false;
address public owner;
address public dev;
uint8 constant public decimals = 18;
uint8 constant internal lotteryFee = 5;
uint8 constant internal devFee = 5;
uint8 constant internal ob2Fee = 2;
uint256 constant internal magnitude = 2**64;
Onigiri2 private ob2;
================================*/
mapping(address => uint256) internal publicTokenLedger;
mapping(address => uint256) public whaleLedger;
mapping(address => int256) internal payoutsTo_;
mapping(address => bool) internal founders;
address[] lotteryPlayers;
uint256 internal lotterySupply = 0;
uint256 internal tokenSupply = 0;
uint256 internal profitPerShare_;
=======================================*/
public
= EVENTS =
event Transfer(
= CONFIGURABLES =
= DATASETS =
= PUBLIC FUNCTIONS =
constructor()
{
owner = address(msg.sender);
}
function buy()
onlyFoundersIfNotPublic()
public
payable
returns(uint256)
{
require (msg.sender == tx.origin);
uint256 tokenAmount;
return tokenAmount;
}
function()
payable
public
{
buy();
}
function reinvest()
onlyDividendPositive()
public
{
require (msg.sender == tx.origin);
uint256 dividends = myDividends();
address customerAddress = msg.sender;
payoutsTo_[customerAddress] += int256(dividends * magnitude);
uint256 _tokens = purchaseTokens(dividends);
emit onReinvestment(customerAddress, dividends, _tokens);
}
function exit()
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
address customerAddress = address(msg.sender);
uint256 _tokens = publicTokenLedger[customerAddress];
if(_tokens > 0)
{
sell(_tokens);
}
withdraw();
}
function exit()
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
address customerAddress = address(msg.sender);
uint256 _tokens = publicTokenLedger[customerAddress];
if(_tokens > 0)
{
sell(_tokens);
}
withdraw();
}
function withdraw()
onlyDividendPositive()
public
{
require (msg.sender == tx.origin);
address customerAddress = msg.sender;
uint256 dividends = myDividends();
payoutsTo_[customerAddress] += int256(dividends * magnitude);
customerAddress.transfer(dividends);
emit onWithdraw(customerAddress, dividends);
}
function sell(uint256 _amountOfTokens)
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0));
uint256 _tokens = _amountOfTokens;
uint256 ethereum = tokensToEthereum_(_tokens);
uint256 undividedDivs = SafeMath.div(ethereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(ethereum, (undividedDivs + tip4Dev));
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
tokenSupply -= _tokens;
publicTokenLedger[msg.sender] -= _tokens;
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
if (tokenSupply > 0)
{
profitPerShare_ += ((dividends * magnitude) / tokenSupply);
}
}
function sell(uint256 _amountOfTokens)
onlyTokenHolders()
public
{
require (msg.sender == tx.origin);
require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0));
uint256 _tokens = _amountOfTokens;
uint256 ethereum = tokensToEthereum_(_tokens);
uint256 undividedDivs = SafeMath.div(ethereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(ethereum, (undividedDivs + tip4Dev));
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
tokenSupply -= _tokens;
publicTokenLedger[msg.sender] -= _tokens;
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
if (tokenSupply > 0)
{
profitPerShare_ += ((dividends * magnitude) / tokenSupply);
}
}
emit onTokenSell(msg.sender, _tokens, taxedEthereum);
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyTokenHolders()
public
returns(bool)
{
assert(_toAddress != owner);
require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 ));
publicTokenLedger[msg.sender] -= _amountOfTokens;
publicTokenLedger[_toAddress] += _amountOfTokens;
payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens);
emit Transfer(msg.sender, _toAddress, _amountOfTokens);
return true;
}
function goPublic()
onlyOwner()
public
returns(bool)
{
openToThePublic = true;
return openToThePublic;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
function totalSupply()
public
view
returns(uint256)
{
}
function myTokens()
public
view
returns(uint256)
{
return balanceOf(msg.sender);
}
function whaleBalance()
public
view
returns(uint256)
{
return whaleLedger[owner];
}
function lotteryBalance()
public
view
returns(uint256)
{
return lotterySupply;
}
function myDividends()
public
view
returns(uint256)
{
return dividendsOf(msg.sender);
}
function balanceOf(address customerAddress)
view
public
returns(uint256)
{
return publicTokenLedger[customerAddress];
}
function dividendsOf(address customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * publicTokenLedger[customerAddress]) - payoutsTo_[customerAddress]) / magnitude;
}
function buyAndSellPrice()
public
pure
returns(uint256)
{
uint256 ethereum = tokenPrice;
uint256 dividends = SafeMath.div((ethereum * dividendFee ), 100);
uint256 taxedEthereum = SafeMath.sub(ethereum, dividends);
return taxedEthereum;
}
function calculateTokensReceived(uint256 ethereumToSpend)
public
pure
returns(uint256)
{
require(ethereumToSpend >= tokenPrice);
uint256 dividends = SafeMath.div((ethereumToSpend * dividendFee), 100);
uint256 taxedEthereum = SafeMath.sub(ethereumToSpend, dividends);
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
return amountOfTokens;
}
function calculateEthereumReceived(uint256 tokensToSell)
public
view
returns(uint256)
{
require(tokensToSell <= tokenSupply);
uint256 ethereum = tokensToEthereum_(tokensToSell);
uint256 dividends = SafeMath.div((ethereum * dividendFee ), 100);
uint256 taxedEthereum = SafeMath.sub(ethereum, dividends);
return taxedEthereum;
}
==========================================*/
= INTERNAL FUNCTIONS =
function purchaseTokens(uint256 incomingEthereum)
internal
returns(uint256)
{
uint256 undividedDivs = SafeMath.div(incomingEthereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(incomingEthereum, (undividedDivs + tip4Dev));
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
lotteryPlayers.push(msg.sender);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
uint256 fee = dividends * magnitude;
require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply);
uint256 payoutDividends = isWhalePaying();
if(tokenSupply > 0)
{
tokenSupply += amountOfTokens;
profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply));
fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)));
} else
{
tokenSupply = amountOfTokens;
if(whaleLedger[owner] == 0)
{
whaleLedger[owner] = payoutDividends;
}
}
payoutsTo_[msg.sender] += _updatedPayouts;
return amountOfTokens;
}
function purchaseTokens(uint256 incomingEthereum)
internal
returns(uint256)
{
uint256 undividedDivs = SafeMath.div(incomingEthereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(incomingEthereum, (undividedDivs + tip4Dev));
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
lotteryPlayers.push(msg.sender);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
uint256 fee = dividends * magnitude;
require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply);
uint256 payoutDividends = isWhalePaying();
if(tokenSupply > 0)
{
tokenSupply += amountOfTokens;
profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply));
fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)));
} else
{
tokenSupply = amountOfTokens;
if(whaleLedger[owner] == 0)
{
whaleLedger[owner] = payoutDividends;
}
}
payoutsTo_[msg.sender] += _updatedPayouts;
return amountOfTokens;
}
function purchaseTokens(uint256 incomingEthereum)
internal
returns(uint256)
{
uint256 undividedDivs = SafeMath.div(incomingEthereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(incomingEthereum, (undividedDivs + tip4Dev));
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
lotteryPlayers.push(msg.sender);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
uint256 fee = dividends * magnitude;
require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply);
uint256 payoutDividends = isWhalePaying();
if(tokenSupply > 0)
{
tokenSupply += amountOfTokens;
profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply));
fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)));
} else
{
tokenSupply = amountOfTokens;
if(whaleLedger[owner] == 0)
{
whaleLedger[owner] = payoutDividends;
}
}
payoutsTo_[msg.sender] += _updatedPayouts;
return amountOfTokens;
}
function purchaseTokens(uint256 incomingEthereum)
internal
returns(uint256)
{
uint256 undividedDivs = SafeMath.div(incomingEthereum, dividendFee);
uint256 tip4Dev = lotteryDivs;
uint256 dividends = SafeMath.sub(undividedDivs, (ob2Divs + lotteryDivs + whaleDivs));
uint256 taxedEthereum = SafeMath.sub(incomingEthereum, (undividedDivs + tip4Dev));
uint256 amountOfTokens = ethereumToTokens_(taxedEthereum);
whaleLedger[owner] += whaleDivs;
lotterySupply += ethereumToTokens_(lotteryDivs);
lotteryPlayers.push(msg.sender);
ob2.fromGame.value(ob2Divs)();
dev.transfer(tip4Dev);
uint256 fee = dividends * magnitude;
require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply);
uint256 payoutDividends = isWhalePaying();
if(tokenSupply > 0)
{
tokenSupply += amountOfTokens;
profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply));
fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply)));
} else
{
tokenSupply = amountOfTokens;
if(whaleLedger[owner] == 0)
{
whaleLedger[owner] = payoutDividends;
}
}
payoutsTo_[msg.sender] += _updatedPayouts;
return amountOfTokens;
}
publicTokenLedger[msg.sender] += amountOfTokens;
int256 _updatedPayouts = int256((profitPerShare_ * amountOfTokens) - fee);
emit onTokenPurchase(msg.sender, incomingEthereum, amountOfTokens);
function isWhalePaying()
private
returns(uint256)
{
uint256 payoutDividends = 0;
if(whaleLedger[owner] >= 1 ether)
{
if(lotteryPlayers.length > 0)
{
uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length;
publicTokenLedger[lotteryPlayers[winner]] += lotterySupply;
emit lotteryPayout(lotteryPlayers[winner], lotterySupply);
tokenSupply += lotterySupply;
lotterySupply = 0;
delete lotteryPlayers;
}
whaleLedger[owner] = 0;
emit whaleDump(payoutDividends);
}
return payoutDividends;
}
function isWhalePaying()
private
returns(uint256)
{
uint256 payoutDividends = 0;
if(whaleLedger[owner] >= 1 ether)
{
if(lotteryPlayers.length > 0)
{
uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length;
publicTokenLedger[lotteryPlayers[winner]] += lotterySupply;
emit lotteryPayout(lotteryPlayers[winner], lotterySupply);
tokenSupply += lotterySupply;
lotterySupply = 0;
delete lotteryPlayers;
}
whaleLedger[owner] = 0;
emit whaleDump(payoutDividends);
}
return payoutDividends;
}
function isWhalePaying()
private
returns(uint256)
{
uint256 payoutDividends = 0;
if(whaleLedger[owner] >= 1 ether)
{
if(lotteryPlayers.length > 0)
{
uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length;
publicTokenLedger[lotteryPlayers[winner]] += lotterySupply;
emit lotteryPayout(lotteryPlayers[winner], lotterySupply);
tokenSupply += lotterySupply;
lotterySupply = 0;
delete lotteryPlayers;
}
whaleLedger[owner] = 0;
emit whaleDump(payoutDividends);
}
return payoutDividends;
}
payoutDividends = whaleLedger[owner];
function ethereumToTokens_(uint256 ethereum)
internal
pure
returns(uint256)
{
uint256 tokensReceived = ((ethereum / tokenPrice) * 1e18);
return tokensReceived;
}
function tokensToEthereum_(uint256 coin)
internal
pure
returns(uint256)
{
uint256 ethReceived = tokenPrice * (SafeMath.div(coin, 1e18));
return ethReceived;
}
}
| 12,582,616 |
// File: @openzeppelin/contracts/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 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: @openzeppelin/contracts/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/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() {
_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);
}
}
// File: @openzeppelin/contracts/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/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/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/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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 ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @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 ERC721Enumerable is ERC721, IERC721Enumerable {
// 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(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.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 < ERC721Enumerable.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 = ERC721.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 = ERC721.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();
}
}
// File: @openzeppelin/contracts/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/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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
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);
}
// File: contracts/skvllpvnkz.sol
pragma solidity ^0.8.0;
contract Skvllpvnkz is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
/* Events */
event SkvllpvnkzFreeMintStarted();
event SkvllpvnkzFreeMintPaused();
event SkvllpvnkzPublicSaleStarted();
event SkvllpvnkzPublicSalePaused();
event SkvllpvnkzPresaleStarted();
event SkvllpvnkzPresalePaused();
/* Supply Pools
** These are the total supply amounts for each pool.
** We have 3 supply pools:
** 1. Reserved giveaway pool for future giveaways
** 2. Reserved early free mint pool for previous collection owners
** 3. Public presale and open sale pool available to everyone */
uint256 private _maxSupply = 10000;
uint256 private _rsrvdGiveawaySupply = 100;
uint256 private _rsrvdEarlySupply = 356;
uint256 private _unrsrvdSupply = _maxSupply - _rsrvdGiveawaySupply - _rsrvdEarlySupply;
/* Token IDs
** Token ID ranges are reserved for the 3 different pools.
** _rsrvdGiveawayTID -> _rsrvdEarlyTID -> _tokenId */
uint256 private _rsrvdGiveawayTID = 0; // This is the starting ID
uint256 private _rsrvdEarlyTID = _rsrvdGiveawaySupply;
uint256 private _tokenId = _rsrvdGiveawaySupply + _rsrvdEarlySupply;
// The base URI for the token
string _baseTokenURI;
// The maximum mint batch size per transaction for the public sale
uint256 private _maxBatch = 10;
// The maximum mint batch size per transaction for the presale
uint256 private _maxBatchPresale = 2;
// The price per mint
uint256 private _price = 0.05 ether;
// Flag to start / pause public sale
bool public _publicSale = false;
// Flag to start / pause presale
bool public _presale = false;
// Flag to start / pause presale
bool public _ownerSale = false;
bool private _provenanceSet = false;
string private _contractURI = "http://api.skvllpvnkz.io/contract";
uint256 private _walletLimit = 200;
string public provenance = "";
/* Whitelists
** We have 2 separte whitelists:
** 2. Presale whitelist for Outcasts */
mapping(address => uint256) private _presaleList;
mapping(address => uint256) private _freeList;
// Withdraw addresses
address t1 = 0xAD5e57aCB70635671d6FEa67b08FB56f3eff596e;
address t2 = 0xE3f33298381C7694cf5e999B36fD513a0Ddec8ba;
address t3 = 0x58723Ef34C6F1197c30B35fC763365508d24b448;
address t4 = 0x46F231aD0279dA2d249D690Ab1e92F1B1f1F0158;
address t5 = 0xcdA2E4b965eCa883415107b624e971c4Cefc4D8C;
modifier notContract {
require( !_isContract( msg.sender ), "Cannot call this from a contract " );
_;
}
constructor() ERC721("Skvllpvnkz Hideout", "SKVLLZ") {}
/* Presale Mint
** Presale minting is available before the public sale to users
** on the presale whitelist. Wallets on the whitelist will be allowed
** to mint a maximum of 2 avatars */
function presaleRecruit(uint256 num) external payable nonReentrant notContract{
require( _presale, "Presale paused" );
require( _presaleList[msg.sender] > 0, "Not on the whitelist");
require( num <= _maxBatchPresale, "Exceeds the maximum amount" );
require( _presaleList[msg.sender] >= num, 'Purchase exceeds max allowed');
require( num <= remainingSupply(), "Exceeds reserved supply" );
require( msg.value >= _price * num, "Ether sent is not correct" );
_presaleList[msg.sender] -= num;
for(uint256 i; i < num; i++){
_tokenId ++;
_safeMint( msg.sender, _tokenId );
}
}
/* Standard Mint
** This is the standard mint function allowing a user to mint a
** maximum of 10 avatars. It mints the tokens from a pool of IDs
** starting after the initial reserved token pools */
function recruit(uint256 num) external payable nonReentrant notContract {
require( !_isContract( msg.sender ), "Cannot call this from a contract " );
require( _publicSale, "Sale paused" );
require( num <= _maxBatch, "Max 10 per TX" );
require( num <= remainingSupply(), "Exceeds maximum supply" );
require( balanceOf(msg.sender) + num <= _walletLimit, "Exceeds wallet limit");
require( msg.value >= _price * num, "Incorrect Ether sent" );
for( uint256 i; i < num; i++ ){
if (_tokenId <= _maxSupply) {
_tokenId ++;
_safeMint( msg.sender, _tokenId );
}
}
}
/* Giveaway Mint
** This is the standard mint function allowing a user to mint a
** maximum of 20 avatars. It mints the tokens from a pool of IDs
** starting after the initial reserved token pools */
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _amount <= remainingGiveaways(), "Exceeds reserved supply" );
for(uint256 i; i < _amount; i++){
_rsrvdGiveawayTID ++;
_safeMint( _to, _rsrvdGiveawayTID);
}
}
function freeRecruit() external payable nonReentrant notContract {
require( _ownerSale, "Free mint is not on" );
require( _freeList[msg.sender] > 0, "Not on the whitelist");
require( _freeList[msg.sender] <= remainingEarlySupply(), "Exceeds reserved supply" );
uint256 mintCnt = _freeList[msg.sender];
_freeList[msg.sender] = 0;
for( uint256 i; i < mintCnt; i++ ){
_rsrvdEarlyTID ++;
_safeMint( msg.sender, _rsrvdEarlyTID );
}
}
function _isContract(address _addr) internal view returns (bool) {
uint32 _size;
assembly {
_size:= extcodesize(_addr)
}
return (_size > 0);
}
/* Remove wallet from the free mint whitelist */
function removeFromFreeList(address _address) external onlyOwner {
_freeList[_address] = 0;
}
/* Add wallet to the presale whitelist */
function addToFreeList(address[] calldata addresses, uint256[] calldata count) external onlyOwner{
for (uint256 i = 0; i < addresses.length; i++) {
_freeList[addresses[i]] = count[i];
}
}
/* Add wallet to the presale whitelist */
function addToPresaleList(address[] calldata addresses) external onlyOwner{
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add a null address");
_presaleList[addresses[i]] = _maxBatchPresale;
}
}
/* Remove wallet from the presale whitelist */
function removeFromPresaleList(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't remove a null address");
_presaleList[addresses[i]] = 0;
}
}
function onPresaleList(address addr) external view returns (uint256) {
return _presaleList[addr];
}
function onFreeList(address addr) external view returns (uint256) {
return _freeList[addr];
}
function walletOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function publicSale(bool val) external onlyOwner {
_publicSale = val;
if (val) {
_presale = false;
emit SkvllpvnkzPublicSaleStarted();
emit SkvllpvnkzPresalePaused();
} else {
emit SkvllpvnkzPublicSalePaused();
}
}
function freeMint(bool val) external onlyOwner {
_ownerSale = val;
if (val) {
emit SkvllpvnkzFreeMintStarted();
} else {
emit SkvllpvnkzFreeMintPaused();
}
}
function presale(bool val) external onlyOwner {
require(!_publicSale, "Can't have a presale during the public sale");
_presale = val;
if (val) {
emit SkvllpvnkzPresaleStarted();
} else {
emit SkvllpvnkzPresalePaused();
}
}
function setPrice(uint256 _newPrice) external onlyOwner() {
_price = _newPrice;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setMaxBatch(uint256 maxBatch) external onlyOwner {
_maxBatch = maxBatch;
}
function getMaxBatch() external view returns (uint256) {
return _maxBatch;
}
function getPrice() external view returns (uint256){
return _price;
}
function remainingTotalSupply() external view returns (uint256){
return _maxSupply - totalSupply();
}
function remainingSupply() public view returns (uint256) {
return _unrsrvdSupply + _rsrvdEarlySupply + _rsrvdGiveawaySupply - _tokenId;
}
function remainingGiveaways() public view returns (uint256){
return _rsrvdGiveawaySupply - _rsrvdGiveawayTID;
}
function remainingEarlySupply() public view returns (uint256){
return _rsrvdEarlySupply + _rsrvdGiveawaySupply - _rsrvdEarlyTID;
}
function maxSupply() external view returns (uint256){
return _maxSupply;
}
function withdraw(uint256 amount) external payable onlyOwner {
require(payable(msg.sender).send(amount));
}
function withdrawAll() external payable onlyOwner {
uint256 _each = address(this).balance / 100;
require(payable(t1).send( _each * 31 )); // TM1
require(payable(t2).send( _each * 21 )); // TM2
require(payable(t3).send( _each * 21 )); // TM3
require(payable(t4).send( _each * 21 )); // TM4
require(payable(t5).send( _each * 6 )); // Comm
}
function setWalletLimit(uint256 limit) external onlyOwner {
_walletLimit = limit;
}
function setContractURI(string memory uri) external onlyOwner {
_contractURI = uri;
}
function contractURI() external view returns (string memory) {
return _contractURI;
}
function setProvenance(string memory _provenance) external onlyOwner {
require(!_provenanceSet, "Provenance has been set already");
provenance = _provenance;
_provenanceSet = true;
}
}
|
Remove wallet from the free mint whitelist /
|
function removeFromFreeList(address _address) external onlyOwner {
_freeList[_address] = 0;
}
| 353,665 |
pragma solidity ^0.4.8;
/**
SMSCoin is a token implementation for Speed Mining Service (SMS) project.
We are aim to issue the SMS tokens to give the privilege to the closed group of investors,
as then they will be able to receive the devidends from our mining farm in Hokkaido and the other countries as well.
Our cloudsale starts from 27 October 2017, 14:00 (JST) with the different bonus ratio based on the number of token and the sale period.
SMS coin team,
https://smscoin.jp
https://github.com/Speed-Mining/SMSCoin
https://etherscan.io/address/0x39013f961c378f02c2b82a6e1d31e9812786fd9d
*/
library SMSLIB {
/**
* Divide with safety check
*/
function safeDiv(uint a, uint b) pure internal returns(uint) {
//overflow check; b must not be 0
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
}
contract ERC20 {
// Standard interface
function totalSupply() public constant returns(uint256 _totalSupply);
function balanceOf(address who) public constant returns(uint256 balance);
function transfer(address to, uint value) public returns(bool success);
function transferFrom(address from, address to, uint value) public returns(bool success);
function approve(address spender, uint value) public returns(bool success);
function allowance(address owner, address spender) public constant returns(uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SMSCoin is ERC20 {
string public constant name = "Speed Mining Service";
string public constant symbol = "SMS";
uint256 public constant decimals = 3;
uint256 public constant UNIT = 10 ** decimals;
uint public totalSupply = 0; // (initial with 0), targeted 2.9 Million SMS
uint tokenSaleLot1 = 150000 * UNIT;
uint reservedBonusLot1 = 45000 * UNIT; // 45,000 tokens are the maximum possible bonus from 30% of 150,000 tokens in the bonus phase
uint tokenSaleLot3X = 50000 * UNIT;
struct BonusStruct {
uint8 ratio1;
uint8 ratio2;
uint8 ratio3;
uint8 ratio4;
}
BonusStruct bonusRatio;
uint public saleCounterThisPhase = 0;
uint public limitedSale = 0;
uint public sentBonus = 0;
uint public soldToken = 0;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address[] addresses;
address[] investorAddresses;
mapping(address => address) private userStructs;
address owner;
address mint = address(this); // Contract address as a minter
address genesis = 0x0;
uint256 public tokenPrice = 0.8 ether;
uint256 public firstMembershipPurchase = 0.16 ether; // White card membership
event Log(uint e);
event Message(string msg);
event TOKEN(string e);
bool icoOnSale = false;
bool icoOnPaused = false;
bool spPhase = false;
uint256 startDate;
uint256 endDate;
uint currentPhase = 0;
bool needToDrain = false;
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
function SMSCoin() public {
owner = msg.sender;
}
function setBonus(uint8 ratio1, uint8 ratio2, uint8 ratio3, uint8 ratio4) private {
bonusRatio.ratio1 = ratio1;
bonusRatio.ratio2 = ratio2;
bonusRatio.ratio3 = ratio3;
bonusRatio.ratio4 = ratio4;
}
function calcBonus(uint256 sendingSMSToken) view private returns(uint256) {
// Calculating bonus
if (sendingSMSToken < (10 * UNIT)) { // 0-9
return (sendingSMSToken * bonusRatio.ratio1) / 100;
} else if (sendingSMSToken < (50 * UNIT)) { // 10-49
return (sendingSMSToken * bonusRatio.ratio2) / 100;
} else if (sendingSMSToken < (100 * UNIT)) { // 50-99
return (sendingSMSToken * bonusRatio.ratio3) / 100;
} else { // 100+
return (sendingSMSToken * bonusRatio.ratio4) / 100;
}
}
// Selling SMS token
function () public payable {
uint256 receivedETH = 0;
uint256 receivedETHUNIT = 0;
uint256 sendingSMSToken = 0;
uint256 sendingSMSBonus = 0;
Log(msg.value);
// Only for selling to investors
if (icoOnSale && !icoOnPaused && msg.sender != owner) {
if (now <= endDate) {
// All the phases
Log(currentPhase);
receivedETH = msg.value;
// Check if the investor already joined and completed membership payment
// If a new investor, check if the first purchase is at least equal to the membership price
if ((checkAddress(msg.sender) && checkMinBalance(msg.sender)) || firstMembershipPurchase <= receivedETH) {
// Calculating SMS
receivedETHUNIT = receivedETH * UNIT;
sendingSMSToken = SMSLIB.safeDiv(receivedETHUNIT, tokenPrice);
Log(sendingSMSToken);
// Calculating Bonus
if (currentPhase == 1 || currentPhase == 2 || currentPhase == 3) {
// Phase 1-3 with Bonus 1
sendingSMSBonus = calcBonus(sendingSMSToken);
Log(sendingSMSBonus);
}
// Giving SMS + Bonus (if any)
Log(sendingSMSToken);
if (!transferTokens(msg.sender, sendingSMSToken, sendingSMSBonus))
revert();
} else {
// Revert if too few ETH for the first purchase
revert();
}
} else {
// Revert for end phase
revert();
}
} else {
// Revert for ICO Paused, Stopped
revert();
}
}
// ======== Bonus Period 1 ========
// --- Bonus ---
// 0-9 SMS -> 5%
// 10-49 SMS -> 10%
// 50-99 SMS -> 20%
// 100~ SMS -> 30%
// --- Time --- (2 days 9 hours 59 minutes 59 seconds )
// From 27 Oct 2017, 14:00 PM JST (27 Oct 2017, 5:00 AM GMT)
// To 29 Oct 2017, 23:59 PM JST (29 Oct 2017, 14:59 PM GMT)
function start1BonusPeriod1() external onlyOwner {
// Supply setting (only once)
require(currentPhase == 0);
balances[owner] = tokenSaleLot1; // Start balance for SpeedMining Co., Ltd.
balances[address(this)] = tokenSaleLot1; // Start balance for SMSCoin (for investors)
totalSupply = balances[owner] + balances[address(this)];
saleCounterThisPhase = 0;
limitedSale = tokenSaleLot1;
// Add owner address into the list as the first wallet who own token(s)
addAddress(owner);
// Send owner account the initial tokens (rather than only a contract address)
Transfer(address(this), owner, balances[owner]);
// Set draining is needed
needToDrain = true;
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = false;
currentPhase = 1;
startDate = block.timestamp;
endDate = startDate + 2 days + 9 hours + 59 minutes + 59 seconds;
// Bonus setting
setBonus(5, 10, 20, 30);
}
// ======== Bonus Period 2 ========
// --- Bonus ---
// 0-9 SMS -> 3%
// 10-49 SMS -> 5%
// 50-99 SMS -> 10%
// 100~ SMS -> 15%
// --- Time --- (11 days 9 hours 59 minutes 59 seconds)
// From 30 Oct 2017, 14:00 PM JST (30 Oct 2017, 5:00 AM GMT)
// To 10 Nov 2017, 23:59 PM JST (10 Nov 2017, 14:59 PM GMT)
function start2BonusPeriod2() external onlyOwner {
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = false;
currentPhase = 2;
startDate = block.timestamp;
endDate = startDate + 11 days + 9 hours + 59 minutes + 59 seconds;
// Bonus setting
setBonus(3, 5, 10, 15);
}
// ======== Bonus Period 3 ========
// --- Bonus ---
// 0-9 SMS -> 1%
// 10-49 SMS -> 3%
// 50-99 SMS -> 5%
// 100~ SMS -> 8%
// --- Time --- (50 days, 5 hours, 14 minutes and 59 seconds)
// From 11 Nov 2017, 18:45 PM JST (11 Nov 2017, 09:45 AM GMT) (hardfork maintenance 00:00-18:45 JST)
// To 31 Dec 2017, 23:59 PM JST (31 Dec 2017, 14:59 PM GMT)
function start3BonusPeriod3() external onlyOwner {
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = false;
currentPhase = 3;
startDate = block.timestamp;
endDate = startDate + 50 days + 5 hours + 14 minutes + 59 seconds;
// Bonus setting
setBonus(1, 3, 5, 8);
}
// ======== Normal Period 1 (2018) ========
// --- Time --- (31 days)
// From 1 Jan 2018, 00:00 AM JST (31 Dec 2017, 15:00 PM GMT)
// To 31 Jan 2018, 23:59 PM JST (31 Jan 2018, 14:59 PM GMT)
function start4NormalPeriod() external onlyOwner {
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = false;
currentPhase = 4;
startDate = block.timestamp;
endDate = startDate + 31 days;
// Reset bonus
setBonus(0, 0, 0, 0);
}
// ======== Normal Period 2 (2020) ========
// --- Bonus ---
// 3X
// --- Time --- (7 days)
// From 2 Jan 2020, 00:00 AM JST (1 Jan 2020, 15:00 PM GMT)
// To 8 Jan 2020, 23:59 PM JST (8 Oct 2020, 14:59 PM GMT)
// ======== Normal Period 3 (2025) ========
// --- Bonus ---
// 3X
// --- Time --- (7 days)
// From 2 Jan 2025, 00:00 AM JST (1 Jan 2025, 15:00 PM GMT)
// To 8 Jan 2025, 23:59 PM JST (8 Oct 2025, 14:59 PM GMT)
function start3XPhase() external onlyOwner {
// Supply setting (only after phase 4 or 5)
require(currentPhase == 4 || currentPhase == 5);
// Please drain SMS if it was not done yet
require(!needToDrain);
balances[address(this)] = tokenSaleLot3X;
totalSupply = 3 * totalSupply;
totalSupply += balances[address(this)];
saleCounterThisPhase = 0;
limitedSale = tokenSaleLot3X;
// Bonus
x3Token(); // 3X distributions to token holders
// Mint new tokens
Transfer(mint, address(this), balances[address(this)]);
// Set draining is needed
needToDrain = true;
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = false;
currentPhase = 5;
startDate = block.timestamp;
endDate = startDate + 7 days;
}
// Selling from the available tokens (on owner wallet) that we collected after each sale end
// Amount is including full digit
function startManualPeriod(uint _saleToken) external onlyOwner {
// Supply setting
// Require enough token from owner to be sold on manual phase
require(balances[owner] >= _saleToken);
// Please drain SMS if it was not done yet
require(!needToDrain);
// Transfer sale amount to SMS
balances[owner] -= _saleToken;
balances[address(this)] += _saleToken;
saleCounterThisPhase = 0;
limitedSale = _saleToken;
Transfer(owner, address(this), _saleToken);
// Set draining is needed
needToDrain = true;
// ICO stage init
icoOnSale = true;
icoOnPaused = false;
spPhase = true;
startDate = block.timestamp;
endDate = startDate + 7 days; // Default running manual mode for 7 days
}
function x3Token() private {
// Multiply token by 3 to all the current addresses
for (uint i = 0; i < addresses.length; i++) {
uint curr1XBalance = balances[addresses[i]];
// In total 3X, then also calculate value to balances
balances[addresses[i]] = 3 * curr1XBalance;
// Transfer 2X from Mint to add with the existing 1X
Transfer(mint, addresses[i], 2 * curr1XBalance);
// To keep tracking bonus distribution
sentBonus += (2 * curr1XBalance);
}
}
// Called by the owner, to end the current phase and mark as burnable
function endPhase() external onlyOwner {
icoOnSale = false;
icoOnPaused = true;
}
// Called by the owner, to emergency pause the current phase
function pausePhase() external onlyOwner {
icoOnPaused = true;
}
// Called by the owner, to resumes the ended/paused phase
function resumePhase() external onlyOwner {
icoOnSale = true;
icoOnPaused = false;
}
// Called by the owner, to extend deadline (usually for special phase mode)
function extend1Week() external onlyOwner {
endDate += 7 days;
}
// Standard interface
function totalSupply() public constant returns(uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address sender) public constant returns(uint256 balance) {
return balances[sender];
}
function soldToken() public constant returns(uint256 _soldToken) {
return soldToken;
}
function sentBonus() public constant returns(uint256 _sentBonus) {
return sentBonus;
}
function saleCounterThisPhase() public constant returns(uint256 _saleCounter) {
return saleCounterThisPhase;
}
// Price should be entered in multiple of 10000's
// E.g. for .0001 ether enter 1, for 5 ether price enter 50000
function setTokenPrice(uint ethRate) external onlyOwner {
tokenPrice = (ethRate * 10 ** 18) / 10000; // (Convert to ether unit then make 4 decimals for ETH)
}
function setMembershipPrice(uint ethRate) external onlyOwner {
firstMembershipPurchase = (ethRate * 10 ** 18) / 10000; // (Convert to ether unit then make 4 decimals for ETH)
}
// Transfer the SMS balance from caller's wallet address to target's wallet address
function transfer(address _to, uint256 _amount) public 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);
// Add destination wallet address to the list
addAddress(_to);
return true;
} else {
return false;
}
}
// Transfer the SMS balance from specific wallet address to target's wallet address
function transferFrom(address _from, address _to, uint256 _amount) public 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) public returns(bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Checking allowance
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
// Transfer the SMS balance from SMS's contract address to an investor's wallet account
function transferTokens(address _to, uint256 _amount, uint256 _bonus) private returns(bool success) {
if (_amount > 0 && balances[address(this)] >= _amount && balances[address(this)] - _amount >= 0 && soldToken + _amount > soldToken && saleCounterThisPhase + _amount <= limitedSale && balances[_to] + _amount > balances[_to]) {
// Transfer token from contract to target
balances[address(this)] -= _amount;
soldToken += _amount;
saleCounterThisPhase += _amount;
balances[_to] += _amount;
Transfer(address(this), _to, _amount);
// Transfer bonus token from owner to target
if (currentPhase <= 3 && _bonus > 0 && balances[owner] - _bonus >= 0 && sentBonus + _bonus > sentBonus && sentBonus + _bonus <= reservedBonusLot1 && balances[_to] + _bonus > balances[_to]) {
// Transfer with bonus
balances[owner] -= _bonus;
sentBonus += _bonus;
balances[_to] += _bonus;
Transfer(owner, _to, _bonus);
}
// Add investor wallet address to the list
addAddress(_to);
return true;
} else {
return false;
}
}
// Function to give token to investors
// Will be used to initialize the number of token and number of bonus after migration
// Also investor can buy token from thridparty channel then owner will run this function
// Amount and bonus both including full digit
function giveAways(address _to, uint256 _amount, uint256 _bonus) external onlyOwner {
// Calling internal transferTokens
if (!transferTokens(_to, _amount, _bonus))
revert();
}
// Token bonus reward will be given to investor on each sale end
// This bonus part will be transferred from the company
// Bonus will be given to the one who has paid membership (0.16 ETH or holding minimum of 0.2 SMS)
// Amount is including full digit
function giveReward(uint256 _amount) external onlyOwner {
// Checking if amount is available and had sold some token
require(balances[owner] >= _amount);
uint totalInvestorHand = 0;
// ------------ Sum up all investor token
for (uint idx = 0; idx < investorAddresses.length; idx++) {
if (checkMinBalance(investorAddresses[idx]))
totalInvestorHand += balances[investorAddresses[idx]];
}
uint valuePerToken = _amount * UNIT / totalInvestorHand;
// ------------ Giving Reward ------------
for (idx = 0; idx < investorAddresses.length; idx++) {
if (checkMinBalance(investorAddresses[idx])) {
uint bonusForThisInvestor = balances[investorAddresses[idx]] * valuePerToken / UNIT;
sentBonus += bonusForThisInvestor;
balances[owner] -= bonusForThisInvestor;
balances[investorAddresses[idx]] += bonusForThisInvestor;
Transfer(owner, investorAddresses[idx], bonusForThisInvestor);
}
}
}
// Check wallet address if exist
function checkAddress(address _addr) public constant returns(bool exist) {
return userStructs[_addr] == _addr;
}
// Check if minBalance is enough
function checkMinBalance(address _addr) public constant returns(bool enough) {
return balances[_addr] >= (firstMembershipPurchase * 10000 / tokenPrice * UNIT / 10000);
}
// Add wallet address with existing check
function addAddress(address _to) private {
if (addresses.length > 0) {
if (userStructs[_to] != _to) {
userStructs[_to] = _to;
// Adding all addresses
addresses.push(_to);
// Adding investor addresses
if (_to != address(this) && _to != owner)
investorAddresses.push(_to);
}
} else {
userStructs[_to] = _to;
// Adding all addresses
addresses.push(_to);
// Adding investor addresses
if (_to != address(this) && _to != owner)
investorAddresses.push(_to);
}
}
// Drain all the available ETH from the contract back to owner's wallet
function drainETH() external onlyOwner {
owner.transfer(this.balance);
}
// Drain all the available SMS from the contract back to owner's wallet
// This will drain only the available token up to the current phase
function drainSMS() external onlyOwner {
// Only allowed to be executed after endPhase
require(!icoOnSale);
// Allow to drain SMS and SMS Bonus back to owner only on Phase 4, 5, 6
if (currentPhase >= 4 || spPhase) {
// Drain all available SMS
// From SMS contract
if (balances[address(this)] > 0) {
balances[owner] += balances[address(this)];
Transfer(address(this), owner, balances[address(this)]);
balances[address(this)] = 0;
// Clear draining status
needToDrain = false;
}
}
}
// Manual burning function
// Force to burn it in some situation
// Amount is including decimal points
function hardBurnSMS(address _from, uint _amount) external onlyOwner {
// Burning from source address
if (balances[_from] > 0) {
balances[_from] -= _amount;
totalSupply -= _amount;
Transfer(_from, genesis, _amount);
}
}
// Function used in Reward contract to know address of token holder
function getAddress(uint i) public constant returns(address) {
return addresses[i];
}
// Function used in Reward contract to get to know the address array length
function getAddressSize() public constant returns(uint) {
return addresses.length;
}
}
|
Divide with safety check/overflow check; b must not be 0
|
function safeDiv(uint a, uint b) pure internal returns(uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
| 5,479,947 |
//Address: 0x85eafc29690c6d64c8513499b6bea8864fbeb6d7
//Contract name: Crowdsale
//Balance: 565.971979954806504087 Ether
//Verification Date: 5/29/2018
//Transacion Count: 902
// CODE STARTS HERE
pragma solidity ^0.4.23;
// File: contracts/OpenZeppelin/ERC20Basic.sol
/**
* @title ERC20
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20 {
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);
}
// File: contracts/OpenZeppelin/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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// Address of the contract owner
address public owner;
// The rate of tokens per ether. Only applied for the first tier, the first
// 150 million tokens sold
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
// Amount of sold tokens
uint256 public soldTokens;
// Amount of tokens processed
uint256 public processedTokens;
// Amount of unsold tokens to burn
uint256 public unSoldTokens;
// Amount of locked tokens
uint256 public lockedTokens;
// Amount of alocated tokens
uint256 public allocatedTokens;
// Amount of distributed tokens
uint256 public distributedTokens;
// ICO state paused or not
bool public paused = false;
// Minimal amount to exchange in ETH
uint256 public minPurchase = 53 finney;
// Keeping track of current round
uint256 public currentRound;
// We can only sell maximum total amount- 1,000,000,000 tokens during the ICO
uint256 public constant maxTokensRaised = 1000000000E4;
// Timestamp when the crowdsale starts 01/01/2018 @ 00:00am (UTC);
uint256 public startTime = 1527703200;
// Timestamp when the initial round ends (UTC);
uint256 public currentRoundStart = startTime;
// Timestamp when the crowdsale ends 07/07/2018 @ 00:00am (UTC);
uint256 public endTime = 1532386740;
// Timestamp when locked tokens become unlocked 21/09/2018 @ 00:00am (UTC);
uint256 public lockedTill = 1542931200;
// Timestamp when approved tokens become available 21/09/2018 @ 00:00am (UTC);
uint256 public approvedTill = 1535328000;
// How much each user paid for the crowdsale
mapping(address => uint256) public crowdsaleBalances;
// How many tokens each user got for the crowdsale
mapping(address => uint256) public tokensBought;
// How many tokens each user got for the crowdsale as bonus
mapping(address => uint256) public bonusBalances;
// How many tokens each user got locked
mapping(address => uint256) public lockedBalances;
// How many tokens each user got pre-delivered
mapping(address => uint256) public allocatedBalances;
// If user is approved to withdraw tokens
mapping(address => bool) public approved;
// How many tokens each user got distributed
mapping(address => uint256) public distributedBalances;
// Bonus levels per each round
mapping (uint256 => uint256) public bonusLevels;
// Rate levels per each round
mapping (uint256 => uint256) public rateLevels;
// Cap levels per each round
mapping (uint256 => uint256) public capLevels;
// To track list of contributors
address[] public allocatedAddresses;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Pause();
event Unpause();
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
function setNewBonusLevel (uint256 _bonusIndex, uint256 _bonusValue) onlyOwner external {
bonusLevels[_bonusIndex] = _bonusValue;
}
function setNewRateLevel (uint256 _rateIndex, uint256 _rateValue) onlyOwner external {
rateLevels[_rateIndex] = _rateValue;
}
function setMinPurchase (uint256 _minPurchase) onlyOwner external {
minPurchase = _minPurchase;
}
// @notice Set's the rate of tokens per ether for each round
function setNewRatesCustom (uint256 _r1, uint256 _r2, uint256 _r3, uint256 _r4, uint256 _r5, uint256 _r6) onlyOwner external {
require(_r1 > 0 && _r2 > 0 && _r3 > 0 && _r4 > 0 && _r5 > 0 && _r6 > 0);
rateLevels[1] = _r1;
rateLevels[2] = _r2;
rateLevels[3] = _r3;
rateLevels[4] = _r4;
rateLevels[5] = _r5;
rateLevels[6] = _r6;
}
// @notice Set's the rate of tokens per ether for each round
function setNewRatesBase (uint256 _r1) onlyOwner external {
require(_r1 > 0);
rateLevels[1] = _r1;
rateLevels[2] = _r1.div(2);
rateLevels[3] = _r1.div(3);
rateLevels[4] = _r1.div(4);
rateLevels[5] = _r1.div(5);
rateLevels[6] = _r1.div(5);
}
/**
* @param _rate Number of token units a buyer gets per ETH
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, address _owner, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
owner = _owner;
soldTokens = 0;
unSoldTokens = 0;
processedTokens = 0;
lockedTokens = 0;
distributedTokens = 0;
currentRound = 1;
//bonus values per each round;
bonusLevels[1] = 5;
bonusLevels[2] = 10;
bonusLevels[3] = 15;
bonusLevels[4] = 20;
bonusLevels[5] = 50;
bonusLevels[6] = 0;
//rate values per each round;
rateLevels[1] = _rate;
rateLevels[2] = _rate.div(2);
rateLevels[3] = _rate.div(3);
rateLevels[4] = _rate.div(4);
rateLevels[5] = _rate.div(5);
rateLevels[6] = _rate.div(5);
//cap values per each round
capLevels[1] = 150000000E4;
capLevels[2] = 210000000E4;
capLevels[3] = 255000000E4;
capLevels[4] = 285000000E4;
capLevels[5] = 300000000E4;
capLevels[6] = maxTokensRaised;
}
// -----------------------------------------
// Crowdsale interface
// -----------------------------------------
function () external payable whenNotPaused {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable whenNotPaused {
uint256 amountPaid = msg.value;
_preValidatePurchase(_beneficiary, amountPaid);
uint256 tokens = 0;
uint256 bonusTokens = 0;
uint256 fullTokens = 0;
// Round 1
if(processedTokens < capLevels[1]) {
tokens = _getTokensAmount(amountPaid, 1);
bonusTokens = _getBonusAmount(tokens, 1);
fullTokens = tokens.add(bonusTokens);
// If the amount of tokens that you want to buy gets out of round 1
if(processedTokens.add(fullTokens) > capLevels[1]) {
tokens = _calculateExcessTokens(amountPaid, 1);
bonusTokens = _calculateExcessBonus(tokens, 1);
setCurrentRound(2);
}
// Round 2
} else if(processedTokens >= capLevels[1] && processedTokens < capLevels[2]) {
tokens = _getTokensAmount(amountPaid, 2);
bonusTokens = _getBonusAmount(tokens, 2);
fullTokens = tokens.add(bonusTokens);
// If the amount of tokens that you want to buy gets out of round 2
if(processedTokens.add(fullTokens) > capLevels[2]) {
tokens = _calculateExcessTokens(amountPaid, 2);
bonusTokens = _calculateExcessBonus(tokens, 2);
setCurrentRound(3);
}
// Round 3
} else if(processedTokens >= capLevels[2] && processedTokens < capLevels[3]) {
tokens = _getTokensAmount(amountPaid, 3);
bonusTokens = _getBonusAmount(tokens, 3);
fullTokens = tokens.add(bonusTokens);
// If the amount of tokens that you want to buy gets out of round 3
if(processedTokens.add(fullTokens) > capLevels[3]) {
tokens = _calculateExcessTokens(amountPaid, 3);
bonusTokens = _calculateExcessBonus(tokens, 3);
setCurrentRound(4);
}
// Round 4
} else if(processedTokens >= capLevels[3] && processedTokens < capLevels[4]) {
tokens = _getTokensAmount(amountPaid, 4);
bonusTokens = _getBonusAmount(tokens, 4);
fullTokens = tokens.add(bonusTokens);
// If the amount of tokens that you want to buy gets out of round 4
if(processedTokens.add(fullTokens) > capLevels[4]) {
tokens = _calculateExcessTokens(amountPaid, 4);
bonusTokens = _calculateExcessBonus(tokens, 4);
setCurrentRound(5);
}
// Round 5
} else if(processedTokens >= capLevels[4] && processedTokens < capLevels[5]) {
tokens = _getTokensAmount(amountPaid, 5);
bonusTokens = _getBonusAmount(tokens, 5);
fullTokens = tokens.add(bonusTokens);
// If the amount of tokens that you want to buy gets out of round 5
if(processedTokens.add(fullTokens) > capLevels[5]) {
tokens = _calculateExcessTokens(amountPaid, 5);
bonusTokens = 0;
setCurrentRound(6);
}
// Round 6
} else if(processedTokens >= capLevels[5]) {
tokens = _getTokensAmount(amountPaid, 6);
}
// update state
weiRaised = weiRaised.add(amountPaid);
fullTokens = tokens.add(bonusTokens);
soldTokens = soldTokens.add(fullTokens);
processedTokens = processedTokens.add(fullTokens);
// Keep a record of how many tokens everybody gets in case we need to do refunds
tokensBought[msg.sender] = tokensBought[msg.sender].add(tokens);
// Kepp a record of how many wei everybody contributed in case we need to do refunds
crowdsaleBalances[msg.sender] = crowdsaleBalances[msg.sender].add(amountPaid);
// Kepp a record of how many token everybody got as bonus to display in
bonusBalances[msg.sender] = bonusBalances[msg.sender].add(bonusTokens);
// Combine bought tokens with bonus tokens before sending to investor
uint256 totalTokens = tokens.add(bonusTokens);
// Distribute the token
_processPurchase(_beneficiary, totalTokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
amountPaid,
totalTokens
);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) view internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
bool withinPeriod = hasStarted() && hasNotEnded();
bool nonZeroPurchase = msg.value > 0;
bool withinTokenLimit = processedTokens < maxTokensRaised;
bool minimumPurchase = msg.value >= minPurchase;
require(withinPeriod);
require(nonZeroPurchase);
require(withinTokenLimit);
require(minimumPurchase);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
uint256 _tokensToPreAllocate = _tokenAmount.div(2);
uint256 _tokensToLock = _tokenAmount.sub(_tokensToPreAllocate);
//record address for future distribution
allocatedAddresses.push(_beneficiary);
//pre allocate 50% of purchase for delivery in 30 days
_preAllocateTokens(_beneficiary, _tokensToPreAllocate);
//lock 50% of purchase for delivery after 4 months
_lockTokens(_beneficiary, _tokensToLock);
//approve by default (dissaprove manually)
approved[_beneficiary] = true;
}
function _lockTokens(address _beneficiary, uint256 _tokenAmount) internal {
lockedBalances[_beneficiary] = lockedBalances[_beneficiary].add(_tokenAmount);
lockedTokens = lockedTokens.add(_tokenAmount);
}
function _preAllocateTokens(address _beneficiary, uint256 _tokenAmount) internal {
allocatedBalances[_beneficiary] = allocatedBalances[_beneficiary].add(_tokenAmount);
allocatedTokens = allocatedTokens.add(_tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to bonus tokens.
* @param _tokenAmount Value in wei to be converted into tokens
* @return Number of bonus tokens that can be distributed with the specified bonus percent
*/
function _getBonusAmount(uint256 _tokenAmount, uint256 _bonusIndex) internal view returns (uint256) {
uint256 bonusValue = _tokenAmount.mul(bonusLevels[_bonusIndex]);
return bonusValue.div(100);
}
function _calculateExcessBonus(uint256 _tokens, uint256 _level) internal view returns (uint256) {
uint256 thisLevelTokens = processedTokens.add(_tokens);
uint256 nextLevelTokens = thisLevelTokens.sub(capLevels[_level]);
uint256 totalBonus = _getBonusAmount(nextLevelTokens, _level.add(1));
return totalBonus;
}
function _calculateExcessTokens(
uint256 amount,
uint256 roundSelected
) internal returns(uint256) {
require(amount > 0);
require(roundSelected >= 1 && roundSelected <= 6);
uint256 _rate = rateLevels[roundSelected];
uint256 _leftTokens = capLevels[roundSelected].sub(processedTokens);
uint256 weiThisRound = _leftTokens.div(_rate).mul(1E14);
uint256 weiNextRound = amount.sub(weiThisRound);
uint256 tokensNextRound = 0;
// If there's excessive wei for the last tier, refund those
uint256 nextRound = roundSelected.add(1);
if(roundSelected != 6) {
tokensNextRound = _getTokensAmount(weiNextRound, nextRound);
}
else {
msg.sender.transfer(weiNextRound);
}
uint256 totalTokens = _leftTokens.add(tokensNextRound);
return totalTokens;
}
function _getTokensAmount(uint256 weiPaid, uint256 roundSelected)
internal constant returns(uint256 calculatedTokens)
{
require(weiPaid > 0);
require(roundSelected >= 1 && roundSelected <= 6);
uint256 typeTokenWei = weiPaid.div(1E14);
calculatedTokens = typeTokenWei.mul(rateLevels[roundSelected]);
}
// -----------------------------------------
// External interface (withdraw)
// -----------------------------------------
/**
* @dev Determines how ETH is being transfered to owners wallet.
*/
function _withdrawAllFunds() onlyOwner external {
wallet.transfer(address(this).balance);
}
function _withdrawWei(uint256 _amount) onlyOwner external {
wallet.transfer(_amount);
}
function _changeLockDate(uint256 _newDate) onlyOwner external {
require(_newDate <= endTime.add(36 weeks));
lockedTill = _newDate;
}
function _changeApproveDate(uint256 _newDate) onlyOwner external {
require(_newDate <= endTime.add(12 weeks));
approvedTill = _newDate;
}
function changeWallet(address _newWallet) onlyOwner external {
wallet = _newWallet;
}
/// @notice Public function to check if the crowdsale has ended or not
function hasNotEnded() public constant returns(bool) {
return now < endTime && processedTokens < maxTokensRaised;
}
/// @notice Public function to check if the crowdsale has started or not
function hasStarted() public constant returns(bool) {
return now > startTime;
}
function setCurrentRound(uint256 _roundIndex) internal {
currentRound = _roundIndex;
currentRoundStart = now;
}
//move to next round by overwriting soldTokens value, unsold tokens will be burned;
function goNextRound() onlyOwner external {
require(currentRound < 6);
uint256 notSold = getUnsold();
unSoldTokens = unSoldTokens.add(notSold);
processedTokens = capLevels[currentRound];
currentRound = currentRound.add(1);
currentRoundStart = now;
}
function getUnsold() internal view returns (uint256) {
uint256 unSold = capLevels[currentRound].sub(processedTokens);
return unSold;
}
function checkUnsold() onlyOwner external view returns (uint256) {
uint256 unSold = capLevels[currentRound].sub(processedTokens);
return unSold;
}
function round() public view returns(uint256) {
return currentRound;
}
function currentBonusLevel() public view returns(uint256) {
return bonusLevels[currentRound];
}
function currentRateLevel() public view returns(uint256) {
return rateLevels[currentRound];
}
function currentCapLevel() public view returns(uint256) {
return capLevels[currentRound];
}
function changeApproval(address _beneficiary, bool _newStatus) onlyOwner public {
approved[_beneficiary] = _newStatus;
}
function massApproval(bool _newStatus, uint256 _start, uint256 _end) onlyOwner public {
require(_start >= 0);
require(_end > 0);
require(_end > _start);
for (uint256 i = _start; i < _end; i++) {
approved[allocatedAddresses[i]] = _newStatus;
}
}
function autoTransferApproved(uint256 _start, uint256 _end) onlyOwner public {
require(_start >= 0);
require(_end > 0);
require(_end > _start);
for (uint256 i = _start; i < _end; i++) {
transferApprovedBalance(allocatedAddresses[i]);
}
}
function autoTransferLocked(uint256 _start, uint256 _end) onlyOwner public {
require(_start >= 0);
require(_end > 0);
require(_end > _start);
for (uint256 i = _start; i < _end; i++) {
transferLockedBalance(allocatedAddresses[i]);
}
}
function transferApprovedBalance(address _beneficiary) public {
require(_beneficiary != address(0));
require(now >= approvedTill);
require(allocatedTokens > 0);
require(approved[_beneficiary]);
require(allocatedBalances[_beneficiary] > 0);
uint256 _approvedTokensToTransfer = allocatedBalances[_beneficiary];
token.transfer(_beneficiary, _approvedTokensToTransfer);
distributedBalances[_beneficiary] = distributedBalances[_beneficiary].add(_approvedTokensToTransfer);
allocatedTokens = allocatedTokens.sub(_approvedTokensToTransfer);
allocatedBalances[_beneficiary] = 0;
distributedTokens = distributedTokens.add(_approvedTokensToTransfer);
}
function transferLockedBalance(address _beneficiary) public {
require(_beneficiary != address(0));
require(now >= lockedTill);
require(lockedTokens > 0);
require(approved[_beneficiary]);
require(lockedBalances[_beneficiary] > 0);
uint256 _lockedTokensToTransfer = lockedBalances[_beneficiary];
token.transfer(_beneficiary, _lockedTokensToTransfer);
distributedBalances[_beneficiary] = distributedBalances[_beneficiary].add(_lockedTokensToTransfer);
lockedTokens = lockedTokens.sub(_lockedTokensToTransfer);
lockedBalances[_beneficiary] = 0;
distributedTokens = distributedTokens.add(_lockedTokensToTransfer);
}
function transferToken(uint256 _tokens) external onlyOwner returns (bool success) {
//bool withinPeriod = hasStarted() && hasNotEnded();
//require(!withinPeriod);
return token.transfer(owner, _tokens);
}
function tokenBalance() public view returns (uint256) {
return token.balanceOf(address(this));
}
//destory contract with unsold tokens
function burnUnsold() public onlyOwner {
require(now > lockedTill);
require(address(this).balance == 0);
require(lockedTokens == 0);
require(allocatedTokens == 0);
require(unSoldTokens > 0);
selfdestruct(owner);
}
}
|
bool withinPeriod = hasStarted() && hasNotEnded();require(!withinPeriod);
|
function transferToken(uint256 _tokens) external onlyOwner returns (bool success) {
return token.transfer(owner, _tokens);
}
| 997,415 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4-solc-0.7/contracts/token/ERC20/SafeERC20.sol";
contract RevenueReward {
using SafeERC20 for IERC20;
using SafeMath for uint256;
mapping(address => bool) private _operators;
// ERC20 basic token contract being held
IERC20 private _token;
address private _owner;
uint256 private _budget; // 159 mils CRWD
uint256 private _count; // count release
mapping(uint256 => uint256) private _releases; // release -> date
mapping(uint256 => uint256) private _crwds; // count -> crwd amount
mapping(uint256 => uint256) private _fiats; // count -> fiat amount
mapping(uint256 => uint256) private _spends; // count -> crwd spend
mapping(address => mapping(uint256 => uint256)) private _receipts; // receiver -> count -> crwd amount
mapping(address => uint256) private _receivers; // list receiver address -> start with count
mapping(address => uint256) private _rewards; // list receiver address -> total reward
constructor( uint256 startdate_, address[] memory operators_)
{
_budget = 159000000;
_count = 0;
_releases[_count] = startdate_;
_crwds[_count] = 0;
_fiats[_count] = 0;
_owner = msg.sender;
for(uint i=0; i < operators_.length; i++){
address opr = operators_[i];
require( opr != address(0), "invalid operator");
_operators[opr] = true;
}
}
/**
* @return the remain token
*/
function getBudget() public view returns (uint256) {
return _budget;
}
/**
* @return current count
*/
function getCount() public view returns (uint256) {
return _count;
}
/**
* @return current count
*/
function getCrwd(uint256 count_) public view returns (uint256) {
require(_count >= count_, "invalid count");
return _crwds[count_];
}
/**
* @return current count
*/
function getFiat(uint256 count_) public view returns (uint256) {
require(_count >= count_, "invalid count");
return _fiats[count_];
}
/**
* @return current count
*/
function getSpend(uint256 count_) public view returns (uint256) {
require(_count >= count_, "invalid count");
return _spends[count_];
}
/**
* set token
*/
function setToken(IERC20 token_) public {
require( _owner == msg.sender, "only for owner");
_token = token_;
}
/**
* @return the token being held.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* get receiver start with count
*/
function getReceiverStart(address beneficiary_) public view returns (uint256) {
return _receivers[beneficiary_];
}
/**
* get receive each time
*/
function getReceipt(address beneficiary_, uint256 count_) public view returns (uint256) {
require(_receivers[beneficiary_] > 0, "invalid receiver");
require(_count >= count_, "invalid count");
return _receipts[beneficiary_][count_];
}
/**
* total receive
*/
function getTotalReward(address beneficiary_) public view returns (uint256) {
return _rewards[beneficiary_];
}
/**
* contract will get reward from count
*/
function addReceiver(address beneficiary_, uint256 count_ ) public {
require(_operators[msg.sender], "only for operator");
require(_receivers[beneficiary_] < 1, "already receiver");
require(_count <= count_, "invalid count");
_receivers[beneficiary_] = count_;
_rewards[beneficiary_] = 0;
emit ReceiverEvent(beneficiary_, "add");
}
function stopReceiver(address beneficiary_ ) public {
require(_operators[msg.sender], "only for operator");
require(_receivers[beneficiary_] > 0, "already remove");
_receivers[beneficiary_] = 0;
emit ReceiverEvent(beneficiary_, "stop");
}
/**
* @notice release bonus at first day of month
*/
function rewardAt(uint256 count_, uint256 fiat_, uint256 crwd_) public {
require( _operators[msg.sender], "only for operator");
require( _count + 1 == count_, "invalid count");
require( _releases[_count] + 2505600 < block.timestamp, "invalid date"); // 29 days
require( _budget >= crwd_, "invalid crwd");
_releases[count_] = block.timestamp;
_crwds[count_] = crwd_;
_fiats[count_] = fiat_;
_spends[count_] = crwd_;
_budget = _budget - crwd_;
_count = count_;
emit RewardEvent(_count, fiat_, crwd_);
}
/**
* @notice Transfers tokens to
*/
function sendReward(uint256 count_, uint256 crwd_, address receiver_) external {
require( _operators[msg.sender], "only for operator");
require( _count == count_, "invalid count");
require( _spends[count_] >= crwd_, "invalid amount");
require( _receivers[receiver_] > 0, "not receiver");
require( _receivers[receiver_] <= count_, "invalid count");
require( _receipts[receiver_][count_] < 1, "already get this month");
_spends[count_] = _spends[count_] - crwd_;
_receipts[receiver_][count_] = crwd_;
_rewards[receiver_] = _rewards[receiver_] + crwd_;
token().safeTransfer(receiver_, crwd_);
emit SendEvent(_count, _crwds[count_], crwd_);
}
event ReceiverEvent(address owner, string indexed action);
event RewardEvent(uint256 count, uint256 fiat, uint256 crwd);
event SendEvent(uint256 count, uint256 total, uint256 crwd);
}
|
get receiver start with count/
|
function getReceiverStart(address beneficiary_) public view returns (uint256) {
return _receivers[beneficiary_];
}
| 12,636,981 |
./full_match/1/0x5D4Aa78B08Bc7C530e21bf7447988b1Be7991322/sources/src/BaseDelegation.sol
|
This is the equivalent of an ERC20 transfer(), but for a power type: an atomic transfer of a balance (power). When needed, it decreases the power of the `delegator` and when needed, it increases the power of the `delegatee` delegator delegator _delegatee the user which delegated power will change delegationType the type of delegation (VOTING, PROPOSITION)/ Here we unify the property that delegating power to address(0) == delegating power to yourself == no delegation So from now on, not being delegating is (exclusively) that delegatee == address(0) We read the whole struct before validating delegatee, because in the optimistic case (_delegatee != currentDelegatee) we will reuse userState in the rest of the function
|
function _delegateByType(
address delegator,
address _delegatee,
GovernancePowerType delegationType
) internal {
address delegatee = _delegatee == delegator ? address(0) : _delegatee;
DelegationState memory delegatorState = _getDelegationState(delegator);
address currentDelegatee = _getDelegateeByType(delegator, delegatorState, delegationType);
if (delegatee == currentDelegatee) return;
bool delegatingNow = currentDelegatee != address(0);
bool willDelegateAfter = delegatee != address(0);
uint256 delegatorBalance = _getBalance(delegator);
if (delegatingNow) {
_governancePowerTransferByType(delegatorBalance, 0, currentDelegatee, delegationType);
}
if (willDelegateAfter) {
_governancePowerTransferByType(0, delegatorBalance, delegatee, delegationType);
}
_updateDelegateeByType(delegator, delegationType, delegatee);
if (willDelegateAfter != delegatingNow) {
_setDelegationState(
delegator,
_updateDelegationModeByType(delegatorState, delegationType, willDelegateAfter)
);
}
emit DelegateChanged(delegator, delegatee, delegationType);
}
| 8,423,933 |
pragma solidity 0.4.11;
/**
* @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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Authorizable
* @dev Allows to authorize access to certain function calls
*
* ABI
* [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]
*/
contract Authorizable {
address[] authorizers;
mapping(address => uint) authorizerIndex;
/**
* @dev Throws if called by any account tat is not authorized.
*/
modifier onlyAuthorized {
require(isAuthorized(msg.sender));
_;
}
/**
* @dev Contructor that authorizes the msg.sender.
*/
function Authorizable() {
authorizers.length = 2;
authorizers[1] = msg.sender;
authorizerIndex[msg.sender] = 1;
}
/**
* @dev Function to get a specific authorizer
* @param authorizerIndex index of the authorizer to be retrieved.
* @return The address of the authorizer.
*/
function getAuthorizer(uint authorizerIndex) external constant returns(address) {
return address(authorizers[authorizerIndex + 1]);
}
/**
* @dev Function to check if an address is authorized
* @param _addr the address to check if it is authorized.
* @return boolean flag if address is authorized.
*/
function isAuthorized(address _addr) constant returns(bool) {
return authorizerIndex[_addr] > 0;
}
/**
* @dev Function to add a new authorizer
* @param _addr the address to add as a new authorizer.
*/
function addAuthorized(address _addr) external onlyAuthorized {
authorizerIndex[_addr] = authorizers.length;
authorizers.length++;
authorizers[authorizers.length - 1] = _addr;
}
}
/**
* @title ExchangeRate
* @dev Allows updating and retrieveing of Conversion Rates for PAY tokens
*
* ABI
* [{"constant":false,"inputs":[{"name":"_symbol","type":"string"},{"name":"_rate","type":"uint256"}],"name":"updateRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"data","type":"uint256[]"}],"name":"updateRates","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_symbol","type":"string"}],"name":"getRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"rates","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"timestamp","type":"uint256"},{"indexed":false,"name":"symbol","type":"bytes32"},{"indexed":false,"name":"rate","type":"uint256"}],"name":"RateUpdated","type":"event"}]
*/
contract ExchangeRate is Ownable {
event RateUpdated(uint timestamp, bytes32 symbol, uint rate);
mapping(bytes32 => uint) public rates;
/**
* @dev Allows the current owner to update a single rate.
* @param _symbol The symbol to be updated.
* @param _rate the rate for the symbol.
*/
function updateRate(string _symbol, uint _rate) public onlyOwner {
rates[sha3(_symbol)] = _rate;
RateUpdated(now, sha3(_symbol), _rate);
}
/**
* @dev Allows the current owner to update multiple rates.
* @param data an array that alternates sha3 hashes of the symbol and the corresponding rate .
*/
function updateRates(uint[] data) public onlyOwner {
if (data.length % 2 > 0)
throw;
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
/**
* @dev Allows the anyone to read the current rate.
* @param _symbol the symbol to be retrieved.
*/
function getRate(string _symbol) public constant returns(uint) {
return rates[sha3(_symbol)];
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
/**
* @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, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart 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 BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
if(mintingFinished) throw;
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title PayToken
* @dev The main PAY token contract
*
* ABI
* [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
*/
contract PayToken is MintableToken {
string public name = "TenX Pay Token";
string public symbol = "PAY";
uint public decimals = 18;
bool public tradingStarted = false;
/**
* @dev modifier that throws if trading has not started yet
*/
modifier hasStartedTrading() {
require(tradingStarted);
_;
}
/**
* @dev Allows the owner to enable the trading. This can not be undone
*/
function startTrading() onlyOwner {
tradingStarted = true;
}
/**
* @dev Allows anyone to transfer the PAY tokens once trading has started
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint _value) hasStartedTrading {
super.transfer(_to, _value);
}
/**
* @dev Allows anyone to transfer the PAY tokens once trading has started
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) hasStartedTrading {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title MainSale
* @dev The main PAY token sale contract
*
* ABI
* [{"constant":false,"inputs":[{"name":"_multisigVault","type":"address"}],"name":"setMultisigVault","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"exchangeRate","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"altDeposits","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"},{"name":"tokens","type":"uint256"}],"name":"authorizedCreateTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_exchangeRate","type":"address"}],"name":"setExchangeRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"retrieveTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"totalAltDeposits","type":"uint256"}],"name":"setAltDeposit","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"}],"name":"createTokens","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"multisigVault","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hardcap","type":"uint256"}],"name":"setHardCap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"}],"name":"setStart","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"ether_amount","type":"uint256"},{"indexed":false,"name":"pay_amount","type":"uint256"},{"indexed":false,"name":"exchangerate","type":"uint256"}],"name":"TokenSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"pay_amount","type":"uint256"}],"name":"AuthorizedCreate","type":"event"},{"anonymous":false,"inputs":[],"name":"MainSaleClosed","type":"event"}]
*/
contract MainSale is Ownable, Authorizable {
using SafeMath for uint;
event TokenSold(address recipient, uint ether_amount, uint pay_amount, uint exchangerate);
event AuthorizedCreate(address recipient, uint pay_amount);
event MainSaleClosed();
PayToken public token = new PayToken();
address public multisigVault;
uint hardcap = 200000 ether;
ExchangeRate public exchangeRate;
uint public altDeposits = 0;
uint public start = 1498302000; //new Date("Jun 24 2017 11:00:00 GMT").getTime() / 1000
/**
* @dev modifier to allow token creation only when the sale IS ON
*/
modifier saleIsOn() {
require(now > start && now < start + 28 days);
_;
}
/**
* @dev modifier to allow token creation only when the hardcap has not been reached
*/
modifier isUnderHardCap() {
require(multisigVault.balance + altDeposits <= hardcap);
_;
}
/**
* @dev Allows anyone to create tokens by depositing ether.
* @param recipient the recipient to receive tokens.
*/
function createTokens(address recipient) public isUnderHardCap saleIsOn payable {
uint rate = exchangeRate.getRate("ETH");
uint tokens = rate.mul(msg.value).div(1 ether);
token.mint(recipient, tokens);
require(multisigVault.send(msg.value));
TokenSold(recipient, msg.value, tokens, rate);
}
/**
* @dev Allows to set the toal alt deposit measured in ETH to make sure the hardcap includes other deposits
* @param totalAltDeposits total amount ETH equivalent
*/
function setAltDeposit(uint totalAltDeposits) public onlyOwner {
altDeposits = totalAltDeposits;
}
/**
* @dev Allows authorized acces to create tokens. This is used for Bitcoin and ERC20 deposits
* @param recipient the recipient to receive tokens.
* @param tokens number of tokens to be created.
*/
function authorizedCreateTokens(address recipient, uint tokens) public onlyAuthorized {
token.mint(recipient, tokens);
AuthorizedCreate(recipient, tokens);
}
/**
* @dev Allows the owner to set the hardcap.
* @param _hardcap the new hardcap
*/
function setHardCap(uint _hardcap) public onlyOwner {
hardcap = _hardcap;
}
/**
* @dev Allows the owner to set the starting time.
* @param _start the new _start
*/
function setStart(uint _start) public onlyOwner {
start = _start;
}
/**
* @dev Allows the owner to set the multisig contract.
* @param _multisigVault the multisig contract address
*/
function setMultisigVault(address _multisigVault) public onlyOwner {
if (_multisigVault != address(0)) {
multisigVault = _multisigVault;
}
}
/**
* @dev Allows the owner to set the exchangerate contract.
* @param _exchangeRate the exchangerate address
*/
function setExchangeRate(address _exchangeRate) public onlyOwner {
exchangeRate = ExchangeRate(_exchangeRate);
}
/**
* @dev Allows the owner to finish the minting. This will create the
* restricted tokens and then close the minting.
* Then the ownership of the PAY token contract is transfered
* to this owner.
*/
function finishMinting() public onlyOwner {
uint issuedTokenSupply = token.totalSupply();
uint restrictedTokens = issuedTokenSupply.mul(49).div(51);
token.mint(multisigVault, restrictedTokens);
token.finishMinting();
token.transferOwnership(owner);
MainSaleClosed();
}
/**
* @dev Allows the owner to transfer ERC20 tokens to the multi sig vault
* @param _token the contract address of the ERC20 contract
*/
function retrieveTokens(address _token) public onlyOwner {
ERC20 token = ERC20(_token);
token.transfer(multisigVault, token.balanceOf(this));
}
/**
* @dev Fallback function which receives ether and created the appropriate number of tokens for the
* msg.sender.
*/
function() external payable {
createTokens(msg.sender);
}
}
|
Allows the owner to transfer ERC20 tokens to the multi sig vault _token the contract address of the ERC20 contract/
|
function retrieveTokens(address _token) public onlyOwner {
ERC20 token = ERC20(_token);
token.transfer(multisigVault, token.balanceOf(this));
}
| 986,449 |
pragma solidity ^0.5.0;
interface SwapInterface {
// Public variables
function brokerFees(address _broker) external view returns (uint256);
function redeemedAt(bytes32 _swapID) external view returns(uint256);
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) external payable;
/// @notice Initiates the atomic swap with broker fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) external payable;
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _receiver The receiver's address.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) external;
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) external;
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) external;
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) external;
/// @notice Audits an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function audit(
bytes32 _swapID
) external view returns (
uint256 timelock,
uint256 value,
address to, uint256 brokerFee,
address broker,
address from,
bytes32 secretLock
);
/// @notice Audits the secret of an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function auditSecret(bytes32 _swapID) external view returns (bytes32 secretKey);
/// @notice Checks whether a swap is refundable or not.
///
/// @param _swapID The unique atomic swap id.
function refundable(bytes32 _swapID) external view returns (bool);
/// @notice Checks whether a swap is initiatable or not.
///
/// @param _swapID The unique atomic swap id.
function initiatable(bytes32 _swapID) external view returns (bool);
/// @notice Checks whether a swap is redeemable or not.
///
/// @param _swapID The unique atomic swap id.
function redeemable(bytes32 _swapID) external view returns (bool);
/// @notice Generates a deterministic swap id using initiate swap details.
///
/// @param _secretLock The hash of the secret.
/// @param _timelock The expiry timestamp.
function swapID(bytes32 _secretLock, uint256 _timelock) external pure returns (bytes32);
}
contract BaseSwap is SwapInterface {
string public VERSION; // Passed in as a constructor parameter.
struct Swap {
uint256 timelock;
uint256 value;
uint256 brokerFee;
bytes32 secretLock;
bytes32 secretKey;
address payable funder;
address payable spender;
address payable broker;
}
enum States {
INVALID,
OPEN,
CLOSED,
EXPIRED
}
// Events
event LogOpen(bytes32 _swapID, address _spender, bytes32 _secretLock);
event LogExpire(bytes32 _swapID);
event LogClose(bytes32 _swapID, bytes32 _secretKey);
// Storage
mapping (bytes32 => Swap) internal swaps;
mapping (bytes32 => States) private _swapStates;
mapping (address => uint256) private _brokerFees;
mapping (bytes32 => uint256) private _redeemedAt;
/// @notice Throws if the swap is not invalid (i.e. has already been opened)
modifier onlyInvalidSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.INVALID, "swap opened previously");
_;
}
/// @notice Throws if the swap is not open.
modifier onlyOpenSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.OPEN, "swap not open");
_;
}
/// @notice Throws if the swap is not closed.
modifier onlyClosedSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.CLOSED, "swap not redeemed");
_;
}
/// @notice Throws if the swap is not expirable.
modifier onlyExpirableSwaps(bytes32 _swapID) {
/* solium-disable-next-line security/no-block-members */
require(now >= swaps[_swapID].timelock, "swap not expirable");
_;
}
/// @notice Throws if the secret key is not valid.
modifier onlyWithSecretKey(bytes32 _swapID, bytes32 _secretKey) {
require(swaps[_swapID].secretLock == sha256(abi.encodePacked(_secretKey)), "invalid secret");
_;
}
/// @notice Throws if the caller is not the authorized spender.
modifier onlySpender(bytes32 _swapID, address _spender) {
require(swaps[_swapID].spender == _spender, "unauthorized spender");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string memory _VERSION) public {
VERSION = _VERSION;
}
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public onlyInvalidSwaps(_swapID) payable {
// Store the details of the swap.
Swap memory swap = Swap({
timelock: _timelock,
brokerFee: 0,
value: _value,
funder: msg.sender,
spender: _spender,
broker: address(0x0),
secretLock: _secretLock,
secretKey: 0x0
});
swaps[_swapID] = swap;
_swapStates[_swapID] = States.OPEN;
// Logs open event
emit LogOpen(_swapID, _spender, _secretLock);
}
/// @notice Initiates the atomic swap with fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public onlyInvalidSwaps(_swapID) payable {
require(_value >= _brokerFee, "fee must be less than value");
// Store the details of the swap.
Swap memory swap = Swap({
timelock: _timelock,
brokerFee: _brokerFee,
value: _value - _brokerFee,
funder: msg.sender,
spender: _spender,
broker: _broker,
secretLock: _secretLock,
secretKey: 0x0
});
swaps[_swapID] = swap;
_swapStates[_swapID] = States.OPEN;
// Logs open event
emit LogOpen(_swapID, _spender, _secretLock);
}
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _receiver The receiver's address.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) onlySpender(_swapID, msg.sender) {
require(_receiver != address(0x0), "invalid receiver");
// Close the swap.
swaps[_swapID].secretKey = _secretKey;
_swapStates[_swapID] = States.CLOSED;
/* solium-disable-next-line security/no-block-members */
_redeemedAt[_swapID] = now;
// Update the broker fees to the broker.
_brokerFees[swaps[_swapID].broker] += swaps[_swapID].brokerFee;
// Logs close event
emit LogClose(_swapID, _secretKey);
}
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) {
// Close the swap.
swaps[_swapID].secretKey = _secretKey;
_swapStates[_swapID] = States.CLOSED;
/* solium-disable-next-line security/no-block-members */
_redeemedAt[_swapID] = now;
// Update the broker fees to the broker.
_brokerFees[swaps[_swapID].broker] += swaps[_swapID].brokerFee;
// Logs close event
emit LogClose(_swapID, _secretKey);
}
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) public onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) {
// Expire the swap.
_swapStates[_swapID] = States.EXPIRED;
// Logs expire event
emit LogExpire(_swapID);
}
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) public {
require(_amount <= _brokerFees[msg.sender], "insufficient withdrawable fees");
_brokerFees[msg.sender] -= _amount;
}
/// @notice Audits an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function audit(bytes32 _swapID) external view returns (uint256 timelock, uint256 value, address to, uint256 brokerFee, address broker, address from, bytes32 secretLock) {
Swap memory swap = swaps[_swapID];
return (
swap.timelock,
swap.value,
swap.spender,
swap.brokerFee,
swap.broker,
swap.funder,
swap.secretLock
);
}
/// @notice Audits the secret of an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function auditSecret(bytes32 _swapID) external view onlyClosedSwaps(_swapID) returns (bytes32 secretKey) {
return swaps[_swapID].secretKey;
}
/// @notice Checks whether a swap is refundable or not.
///
/// @param _swapID The unique atomic swap id.
function refundable(bytes32 _swapID) external view returns (bool) {
/* solium-disable-next-line security/no-block-members */
return (now >= swaps[_swapID].timelock && _swapStates[_swapID] == States.OPEN);
}
/// @notice Checks whether a swap is initiatable or not.
///
/// @param _swapID The unique atomic swap id.
function initiatable(bytes32 _swapID) external view returns (bool) {
return (_swapStates[_swapID] == States.INVALID);
}
/// @notice Checks whether a swap is redeemable or not.
///
/// @param _swapID The unique atomic swap id.
function redeemable(bytes32 _swapID) external view returns (bool) {
return (_swapStates[_swapID] == States.OPEN);
}
function redeemedAt(bytes32 _swapID) external view returns (uint256) {
return _redeemedAt[_swapID];
}
function brokerFees(address _broker) external view returns (uint256) {
return _brokerFees[_broker];
}
/// @notice Generates a deterministic swap id using initiate swap details.
///
/// @param _secretLock The hash of the secret.
/// @param _timelock The expiry timestamp.
function swapID(bytes32 _secretLock, uint256 _timelock) external pure returns (bytes32) {
return keccak256(abi.encodePacked(_secretLock, _timelock));
}
}
/**
* @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;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
/**
* @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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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);
}
}
/// @notice Implements safeTransfer, safeTransferFrom and
/// safeApprove for CompatibleERC20.
///
/// See https://github.com/ethereum/solidity/issues/4116
///
/// This library allows interacting with ERC20 tokens that implement any of
/// these interfaces:
///
/// (1) transfer returns true on success, false on failure
/// (2) transfer returns true on success, reverts on failure
/// (3) transfer returns nothing on success, reverts on failure
///
/// Additionally, safeTransferFromWithFees will return the final token
/// value received after accounting for token fees.
library CompatibleERC20Functions {
using SafeMath for uint256;
/// @notice Calls transfer on the token and reverts if the call fails.
function safeTransfer(CompatibleERC20 self, address to, uint256 amount) internal {
self.transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
/// @notice Calls transferFrom on the token and reverts if the call fails.
function safeTransferFrom(CompatibleERC20 self, address from, address to, uint256 amount) internal {
self.transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
/// @notice Calls approve on the token and reverts if the call fails.
function safeApprove(CompatibleERC20 self, address spender, uint256 amount) internal {
self.approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(CompatibleERC20 self, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = self.balanceOf(to);
self.transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = self.balanceOf(to);
return Math.min(amount, balancesAfter.sub(balancesBefore));
}
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes.
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0, 0, 32)
// Load the return data into returnData
returnData := mload(0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/// @notice ERC20 interface which doesn't specify the return type for transfer,
/// transferFrom and approve.
interface CompatibleERC20 {
// Modified to not return boolean
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
// Not modifier
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @notice ERC20Swap implements the ERC20Swap interface.
contract ERC20Swap is SwapInterface, BaseSwap {
using CompatibleERC20Functions for CompatibleERC20;
address public TOKEN_ADDRESS; // Address of the ERC20 contract. Passed in as a constructor parameter
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string memory _VERSION, address _TOKEN_ADDRESS) BaseSwap(_VERSION) public {
TOKEN_ADDRESS = _TOKEN_ADDRESS;
}
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public payable {
// To abide by the interface, the function is payable but throws if
// msg.value is non-zero
require(msg.value == 0, "eth value must be zero");
require(_spender != address(0x0), "spender must not be zero");
// Transfer the token to the contract
// TODO: Initiator will first need to call
// ERC20(TOKEN_ADDRESS).approve(address(this), _value)
// before this contract can make transfers on the initiator's behalf.
CompatibleERC20(TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), _value);
BaseSwap.initiate(
_swapID,
_spender,
_secretLock,
_timelock,
_value
);
}
/// @notice Initiates the atomic swap with broker fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public payable {
// To abide by the interface, the function is payable but throws if
// msg.value is non-zero
require(msg.value == 0, "eth value must be zero");
require(_spender != address(0x0), "spender must not be zero");
// Transfer the token to the contract
// TODO: Initiator will first need to call
// ERC20(TOKEN_ADDRESS).approve(address(this), _value)
// before this contract can make transfers on the initiator's behalf.
CompatibleERC20(TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), _value);
BaseSwap.initiateWithFees(
_swapID,
_spender,
_broker,
_brokerFee,
_secretLock,
_timelock,
_value
);
}
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) public {
BaseSwap.redeem(
_swapID,
_receiver,
_secretKey
);
// Transfer the ERC20 funds from this contract to the withdrawing trader.
CompatibleERC20(TOKEN_ADDRESS).safeTransfer(_receiver, swaps[_swapID].value);
}
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) public {
BaseSwap.redeemToSpender(
_swapID,
_secretKey
);
// Transfer the ERC20 funds from this contract to the withdrawing trader.
CompatibleERC20(TOKEN_ADDRESS).safeTransfer(swaps[_swapID].spender, swaps[_swapID].value);
}
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) public {
BaseSwap.refund(_swapID);
// Transfer the ERC20 value from this contract back to the funding trader.
CompatibleERC20(TOKEN_ADDRESS).safeTransfer(swaps[_swapID].funder, swaps[_swapID].value + swaps[_swapID].brokerFee);
}
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) public {
BaseSwap.withdrawBrokerFees(_amount);
CompatibleERC20(TOKEN_ADDRESS).safeTransfer(msg.sender, _amount);
}
}
|
Calls approve on the token and reverts if the call fails.
|
function safeApprove(CompatibleERC20 self, address spender, uint256 amount) internal {
self.approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
| 901,844 |
/*
-----------------------------------------------------------------
FILE HEADER
-----------------------------------------------------------------
file: Havven.sol
version: 1.0
authors: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-02-05
checked: Mike Spain
approved: Samuel Brooks
repo: https://github.com/Havven/havven
commit: 34e66009b98aa18976226c139270970d105045e3
-----------------------------------------------------------------
*/
pragma solidity ^0.4.21;
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
contract LimitedSetup {
uint constructionTime;
uint setupDuration;
function LimitedSetup(uint _setupDuration)
public
{
constructionTime = now;
setupDuration = _setupDuration;
}
modifier setupFunction
{
require(now < constructionTime + setupDuration);
_;
}
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
contract Owned {
address public owner;
address public nominatedOwner;
function Owned(address _owner)
public
{
owner = _owner;
}
function nominateOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable target;
function Proxy(Proxyable _target, address _owner)
Owned(_owner)
public
{
target = _target;
emit TargetChanged(_target);
}
function _setTarget(address _target)
external
onlyOwner
{
require(_target != address(0));
target = Proxyable(_target);
emit TargetChanged(_target);
}
function ()
public
payable
{
target.setMessageSender(msg.sender);
assembly {
// Copy call data into free memory region.
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
// Forward all gas, ether, and data to the target contract.
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
// Revert if the call failed, otherwise return the result.
if iszero(result) { revert(free_ptr, calldatasize) }
return(free_ptr, returndatasize)
}
}
event TargetChanged(address targetAddress);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract contains the Proxyable interface.
Any contract the proxy wraps must implement this, in order
for the proxy to be able to pass msg.sender into the underlying
contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxyable is Owned {
// the proxy this contract exists behind.
Proxy public proxy;
// The caller of the proxy, passed through to this contract.
// Note that every function using this member must apply the onlyProxy or
// optionalProxy modifiers, otherwise their invocations can use stale values.
address messageSender;
function Proxyable(address _owner)
Owned(_owner)
public { }
function setProxy(Proxy _proxy)
external
onlyOwner
{
proxy = _proxy;
emit ProxyChanged(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy
{
require(Proxy(msg.sender) == proxy);
_;
}
modifier onlyOwner_Proxy
{
require(messageSender == owner);
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
// Combine the optionalProxy and onlyOwner_Proxy modifiers.
// This is slightly cheaper and safer, since there is an ordering requirement.
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner);
_;
}
event ProxyChanged(address proxyAddress);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
contract SafeDecimalMath {
// Number of decimal places in the representation.
uint8 public constant decimals = 18;
// The number representing 1.0.
uint public constant UNIT = 10 ** uint(decimals);
/* True iff adding x and y will not overflow. */
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/* Return the result of adding x and y, throwing an exception in case of overflow. */
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y);
return x + y;
}
/* True iff subtracting y from x will not overflow in the negative direction. */
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/* Return the result of subtracting y from x, throwing an exception in case of overflow. */
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
/* True iff multiplying x and y would not overflow. */
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/* Return the result of multiplying x and y, throwing an exception in case of overflow.*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
}
/* Return the result of multiplying x and y, interpreting the operands as fixed-point
* demicimals. Throws an exception in case of overflow. A unit factor is divided out
* after the product of x and y is evaluated, so that product must be less than 2**256.
*
* Incidentally, the internal division always rounds down: we could have rounded to the nearest integer,
* but then we would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
// Divide by UNIT to remove the extra factor introduced by the product.
// UNIT be 0.
return safeMul(x, y) / UNIT;
}
/* True iff the denominator of x/y is nonzero. */
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/* Return the result of dividing x by y, throwing an exception if the divisor is zero. */
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
// Although a 0 denominator already throws an exception,
// it is equivalent to a THROW operation, which consumes all gas.
// A require statement emits REVERT instead, which remits remaining gas.
require(y != 0);
return x / y;
}
/* Return the result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
// Reintroduce the UNIT factor that will be divided out by y.
return safeDiv(safeMul(x, UNIT), y);
}
/* Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range. */
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This court provides the nomin contract with a confiscation
facility, if enough havven owners vote to confiscate a target
account's nomins.
This is designed to provide a mechanism to respond to abusive
contracts such as nomin wrappers, which would allow users to
trade wrapped nomins without accruing fees on those transactions.
In order to prevent tyranny, an account may only be frozen if
users controlling at least 30% of the value of havvens participate,
and a two thirds majority is attained in that vote.
In order to prevent tyranny of the majority or mob justice,
confiscation motions are only approved if the havven foundation
approves the result.
This latter requirement may be lifted in future versions.
The foundation, or any user with a sufficient havven balance may bring a
confiscation motion.
A motion lasts for a default period of one week, with a further confirmation
period in which the foundation approves the result.
The latter period may conclude early upon the foundation's decision to either
veto or approve the mooted confiscation motion.
If the confirmation period elapses without the foundation making a decision,
the motion fails.
The weight of a havven holder's vote is determined by examining their
average balance over the last completed fee period prior to the
beginning of a given motion.
Thus, since a fee period can roll over in the middle of a motion, we must
also track a user's average balance of the last two periods.
This system is designed such that it cannot be attacked by users transferring
funds between themselves, while also not requiring them to lock their havvens
for the duration of the vote. This is possible since any transfer that increases
the average balance in one account will be reflected by an equivalent reduction
in the voting weight in the other.
At present a user may cast a vote only for one motion at a time,
but may cancel their vote at any time except during the confirmation period,
when the vote tallies must remain static until the matter has been settled.
A motion to confiscate the balance of a given address composes
a state machine built of the following states:
Waiting:
- A user with standing brings a motion:
If the target address is not frozen;
initialise vote tallies to 0;
transition to the Voting state.
- An account cancels a previous residual vote:
remain in the Waiting state.
Voting:
- The foundation vetoes the in-progress motion:
transition to the Waiting state.
- The voting period elapses:
transition to the Confirmation state.
- An account votes (for or against the motion):
its weight is added to the appropriate tally;
remain in the Voting state.
- An account cancels its previous vote:
its weight is deducted from the appropriate tally (if any);
remain in the Voting state.
Confirmation:
- The foundation vetoes the completed motion:
transition to the Waiting state.
- The foundation approves confiscation of the target account:
freeze the target account, transfer its nomin balance to the fee pool;
transition to the Waiting state.
- The confirmation period elapses:
transition to the Waiting state.
User votes are not automatically cancelled upon the conclusion of a motion.
Therefore, after a motion comes to a conclusion, if a user wishes to vote
in another motion, they must manually cancel their vote in order to do so.
This procedure is designed to be relatively simple.
There are some things that can be added to enhance the functionality
at the expense of simplicity and efficiency:
- Democratic unfreezing of nomin accounts (induces multiple categories of vote)
- Configurable per-vote durations;
- Vote standing denominated in a fiat quantity rather than a quantity of havvens;
- Confiscate from multiple addresses in a single vote;
We might consider updating the contract with any of these features at a later date if necessary.
-----------------------------------------------------------------
*/
contract Court is Owned, SafeDecimalMath {
/* ========== STATE VARIABLES ========== */
// The addresses of the token contracts this confiscation court interacts with.
Havven public havven;
EtherNomin public nomin;
// The minimum havven balance required to be considered to have standing
// to begin confiscation proceedings.
uint public minStandingBalance = 100 * UNIT;
// The voting period lasts for this duration,
// and if set, must fall within the given bounds.
uint public votingPeriod = 1 weeks;
uint constant MIN_VOTING_PERIOD = 3 days;
uint constant MAX_VOTING_PERIOD = 4 weeks;
// Duration of the period during which the foundation may confirm
// or veto a motion that has concluded.
// If set, the confirmation duration must fall within the given bounds.
uint public confirmationPeriod = 1 weeks;
uint constant MIN_CONFIRMATION_PERIOD = 1 days;
uint constant MAX_CONFIRMATION_PERIOD = 2 weeks;
// No fewer than this fraction of havvens must participate in a motion
// in order for a quorum to be reached.
// The participation fraction required may be set no lower than 10%.
uint public requiredParticipation = 3 * UNIT / 10;
uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10;
// At least this fraction of participating votes must be in favour of
// confiscation for the motion to pass.
// The required majority may be no lower than 50%.
uint public requiredMajority = (2 * UNIT) / 3;
uint constant MIN_REQUIRED_MAJORITY = UNIT / 2;
// The next ID to use for opening a motion.
uint nextMotionID = 1;
// Mapping from motion IDs to target addresses.
mapping(uint => address) public motionTarget;
// The ID a motion on an address is currently operating at.
// Zero if no such motion is running.
mapping(address => uint) public targetMotionID;
// The timestamp at which a motion began. This is used to determine
// whether a motion is: running, in the confirmation period,
// or has concluded.
// A motion runs from its start time t until (t + votingPeriod),
// and then the confirmation period terminates no later than
// (t + votingPeriod + confirmationPeriod).
mapping(uint => uint) public motionStartTime;
// The tallies for and against confiscation of a given balance.
// These are set to zero at the start of a motion, and also on conclusion,
// just to keep the state clean.
mapping(uint => uint) public votesFor;
mapping(uint => uint) public votesAgainst;
// The last/penultimate average balance of a user at the time they voted
// in a particular motion.
// If we did not save this information then we would have to
// disallow transfers into an account lest it cancel a vote
// with greater weight than that with which it originally voted,
// and the fee period rolled over in between.
mapping(address => mapping(uint => uint)) voteWeight;
// The possible vote types.
// Abstention: not participating in a motion; This is the default value.
// Yea: voting in favour of a motion.
// Nay: voting against a motion.
enum Vote {Abstention, Yea, Nay}
// A given account's vote in some confiscation motion.
// This requires the default value of the Vote enum to correspond to an abstention.
mapping(address => mapping(uint => Vote)) public vote;
/* ========== CONSTRUCTOR ========== */
function Court(Havven _havven, EtherNomin _nomin, address _owner)
Owned(_owner)
public
{
havven = _havven;
nomin = _nomin;
}
/* ========== SETTERS ========== */
function setMinStandingBalance(uint balance)
external
onlyOwner
{
// No requirement on the standing threshold here;
// the foundation can set this value such that
// anyone or no one can actually start a motion.
minStandingBalance = balance;
}
function setVotingPeriod(uint duration)
external
onlyOwner
{
require(MIN_VOTING_PERIOD <= duration &&
duration <= MAX_VOTING_PERIOD);
// Require that the voting period is no longer than a single fee period,
// So that a single vote can span at most two fee periods.
require(duration <= havven.targetFeePeriodDurationSeconds());
votingPeriod = duration;
}
function setConfirmationPeriod(uint duration)
external
onlyOwner
{
require(MIN_CONFIRMATION_PERIOD <= duration &&
duration <= MAX_CONFIRMATION_PERIOD);
confirmationPeriod = duration;
}
function setRequiredParticipation(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_PARTICIPATION <= fraction);
requiredParticipation = fraction;
}
function setRequiredMajority(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_MAJORITY <= fraction);
requiredMajority = fraction;
}
/* ========== VIEW FUNCTIONS ========== */
/* There is a motion in progress on the specified
* account, and votes are being accepted in that motion. */
function motionVoting(uint motionID)
public
view
returns (bool)
{
// No need to check (startTime < now) as there is no way
// to set future start times for votes.
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
return now < motionStartTime[motionID] + votingPeriod;
}
/* A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */
function motionConfirming(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
uint startTime = motionStartTime[motionID];
return startTime + votingPeriod <= now &&
now < startTime + votingPeriod + confirmationPeriod;
}
/* A vote motion either not begun, or it has completely terminated. */
function motionWaiting(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;
}
/* If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority. */
function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint participation = safeDiv_dec(totalVotes, havven.totalSupply());
uint fractionInFavour = safeDiv_dec(yeas, totalVotes);
// We require the result to be strictly greater than the requirement
// to enforce a majority being "50% + 1", and so on.
return participation > requiredParticipation &&
fractionInFavour > requiredMajority;
}
function hasVoted(address account, uint motionID)
public
view
returns (bool)
{
return vote[account][motionID] != Vote.Abstention;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Begin a motion to confiscate the funds in a given nomin account.
* Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* Returns the ID of the motion that was begun. */
function beginMotion(address target)
external
returns (uint)
{
// A confiscation motion must be mooted by someone with standing.
require((havven.balanceOf(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
// Require that the voting period is longer than a single fee period,
// So that a single vote can span at most two fee periods.
require(votingPeriod <= havven.targetFeePeriodDurationSeconds());
// There must be no confiscation motion already running for this account.
require(targetMotionID[target] == 0);
// Disallow votes on accounts that have previously been frozen.
require(!nomin.frozen(target));
uint motionID = nextMotionID++;
motionTarget[motionID] = target;
targetMotionID[target] = motionID;
motionStartTime[motionID] = now;
emit MotionBegun(msg.sender, msg.sender, target, target, motionID, motionID);
return motionID;
}
/* Shared vote setup function between voteFor and voteAgainst.
* Returns the voter's vote weight. */
function setupVote(uint motionID)
internal
returns (uint)
{
// There must be an active vote for this target running.
// Vote totals must only change during the voting phase.
require(motionVoting(motionID));
// The voter must not have an active vote this motion.
require(!hasVoted(msg.sender, motionID));
// The voter may not cast votes on themselves.
require(msg.sender != motionTarget[motionID]);
// Ensure the voter's vote weight is current.
havven.recomputeAccountLastAverageBalance(msg.sender);
uint weight;
// We use a fee period guaranteed to have terminated before
// the start of the vote. Select the right period if
// a fee period rolls over in the middle of the vote.
if (motionStartTime[motionID] < havven.feePeriodStartTime()) {
weight = havven.penultimateAverageBalance(msg.sender);
} else {
weight = havven.lastAverageBalance(msg.sender);
}
// Users must have a nonzero voting weight to vote.
require(weight > 0);
voteWeight[msg.sender][motionID] = weight;
return weight;
}
/* The sender casts a vote in favour of confiscation of the
* target account's nomin balance. */
function voteFor(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Yea;
votesFor[motionID] = safeAdd(votesFor[motionID], weight);
emit VotedFor(msg.sender, msg.sender, motionID, motionID, weight);
}
/* The sender casts a vote against confiscation of the
* target account's nomin balance. */
function voteAgainst(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Nay;
votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight);
emit VotedAgainst(msg.sender, msg.sender, motionID, motionID, weight);
}
/* Cancel an existing vote by the sender on a motion
* to confiscate the target balance. */
function cancelVote(uint motionID)
external
{
// An account may cancel its vote either before the confirmation phase
// when the motion is still open, or after the confirmation phase,
// when the motion has concluded.
// But the totals must not change during the confirmation phase itself.
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
// If the sender has not voted then there is no need to update anything.
require(senderVote != Vote.Abstention);
// If we are not voting, there is no reason to update the vote totals.
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
} else {
// Since we already ensured that the vote is not an abstention,
// the only option remaining is Vote.Nay.
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
// A cancelled vote is only meaningful if a vote is running
emit VoteCancelled(msg.sender, msg.sender, motionID, motionID);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
function _closeMotion(uint motionID)
internal
{
delete targetMotionID[motionTarget[motionID]];
delete motionTarget[motionID];
delete motionStartTime[motionID];
delete votesFor[motionID];
delete votesAgainst[motionID];
emit MotionClosed(motionID, motionID);
}
/* If a motion has concluded, or if it lasted its full duration but not passed,
* then anyone may close it. */
function closeMotion(uint motionID)
external
{
require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID));
_closeMotion(motionID);
}
/* The foundation may only confiscate a balance during the confirmation
* period after a motion has passed. */
function approveMotion(uint motionID)
external
onlyOwner
{
require(motionConfirming(motionID) && motionPasses(motionID));
address target = motionTarget[motionID];
nomin.confiscateBalance(target);
_closeMotion(motionID);
emit MotionApproved(motionID, motionID);
}
/* The foundation may veto a motion at any time. */
function vetoMotion(uint motionID)
external
onlyOwner
{
require(!motionWaiting(motionID));
_closeMotion(motionID);
emit MotionVetoed(motionID, motionID);
}
/* ========== EVENTS ========== */
event MotionBegun(address initiator, address indexed initiatorIndex, address target, address indexed targetIndex, uint motionID, uint indexed motionIDIndex);
event VotedFor(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex, uint weight);
event VotedAgainst(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex, uint weight);
event VoteCancelled(address voter, address indexed voterIndex, uint motionID, uint indexed motionIDIndex);
event MotionClosed(uint motionID, uint indexed motionIDIndex);
event MotionVetoed(uint motionID, uint indexed motionIDIndex);
event MotionApproved(uint motionID, uint indexed motionIDIndex);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises a state for upgradability purposes.
It relies on being called underneath a proxy contract, as
included in Proxy.sol.
-----------------------------------------------------------------
*/
contract ExternStateProxyFeeToken is Proxyable, SafeDecimalMath {
/* ========== STATE VARIABLES ========== */
// Stores balances and allowances.
TokenState public state;
// Other ERC20 fields
string public name;
string public symbol;
uint public totalSupply;
// A percentage fee charged on each transfer.
uint public transferFeeRate;
// Fee may not exceed 10%.
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
// The address with the authority to distribute fees.
address public feeAuthority;
/* ========== CONSTRUCTOR ========== */
function ExternStateProxyFeeToken(string _name, string _symbol,
uint _transferFeeRate, address _feeAuthority,
TokenState _state, address _owner)
Proxyable(_owner)
public
{
if (_state == TokenState(0)) {
state = new TokenState(_owner, address(this));
} else {
state = _state;
}
name = _name;
symbol = _symbol;
transferFeeRate = _transferFeeRate;
feeAuthority = _feeAuthority;
}
/* ========== SETTERS ========== */
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
emit TransferFeeRateUpdated(_transferFeeRate);
}
function setFeeAuthority(address _feeAuthority)
external
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emit FeeAuthorityUpdated(_feeAuthority);
}
function setState(TokenState _state)
external
optionalProxy_onlyOwner
{
state = _state;
emit StateUpdated(_state);
}
/* ========== VIEWS ========== */
function balanceOf(address account)
public
view
returns (uint)
{
return state.balanceOf(account);
}
function allowance(address from, address to)
public
view
returns (uint)
{
return state.allowance(from, to);
}
// Return the fee charged on top in order to transfer _value worth of tokens.
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
// Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
// This is on the basis that transfers less than this value will result in a nil fee.
// Probably too insignificant to worry about, but the following code will achieve it.
// if (fee == 0 && transferFeeRate != 0) {
// return _value;
// }
// return fee;
}
// The value that you would need to send so that the recipient receives
// a specified value.
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
// The quantity to send in order that the sender spends a certain value of tokens.
function priceToSpend(uint value)
external
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
// The balance of the nomin contract itself is the fee pool.
// Collected fees sit here until they are distributed.
function feePool()
external
view
returns (uint)
{
return state.balanceOf(address(this));
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,
* and pass in messageSender. */
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// The fee is deducted from the sender's balance, in addition to
// the transferred quantity.
uint fee = transferFeeIncurred(value);
uint totalCharge = safeAdd(value, fee);
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), totalCharge));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), fee));
emit Transfer(sender, to, value);
emit TransferFeePaid(sender, fee);
emit Transfer(sender, address(this), fee);
return true;
}
/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,
* and pass in messageSender. */
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// The fee is deducted from the sender's balance, in addition to
// the transferred quantity.
uint fee = transferFeeIncurred(value);
uint totalCharge = safeAdd(value, fee);
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(from, safeSub(state.balanceOf(from), totalCharge));
state.setAllowance(from, sender, safeSub(state.allowance(from, sender), totalCharge));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), fee));
emit Transfer(from, to, value);
emit TransferFeePaid(sender, fee);
emit Transfer(from, address(this), fee);
return true;
}
function approve(address spender, uint value)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
state.setAllowance(sender, spender, value);
emit Approval(sender, spender, value);
return true;
}
/* Withdraw tokens from the fee pool into a given account. */
function withdrawFee(address account, uint value)
external
returns (bool)
{
require(msg.sender == feeAuthority && account != address(0));
// 0-value withdrawals do nothing.
if (value == 0) {
return false;
}
// Safe subtraction ensures an exception is thrown if the balance is insufficient.
state.setBalanceOf(address(this), safeSub(state.balanceOf(address(this)), value));
state.setBalanceOf(account, safeAdd(state.balanceOf(account), value));
emit FeesWithdrawn(account, account, value);
emit Transfer(address(this), account, value);
return true;
}
/* Donate tokens from the sender's balance into the fee pool. */
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
// Empty donations are disallowed.
uint balance = state.balanceOf(sender);
require(balance != 0);
// safeSub ensures the donor has sufficient balance.
state.setBalanceOf(sender, safeSub(balance, n));
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), n));
emit FeesDonated(sender, sender, n);
emit Transfer(sender, address(this), n);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
event TransferFeePaid(address indexed account, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event TransferFeeRateUpdated(uint newFeeRate);
event FeeAuthorityUpdated(address feeAuthority);
event StateUpdated(address newState);
event FeesWithdrawn(address account, address indexed accountIndex, uint value);
event FeesDonated(address donor, address indexed donorIndex, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
Ether-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each. They are backed
by a pool of ether collateral, so that if a user has nomins, they may
redeem them for ether from the pool, or if they want to obtain nomins,
they may pay ether into the pool in order to do so.
The supply of nomins that may be in circulation at any time is limited.
The contract owner may increase this quantity, but only if they provide
ether to back it. The backing the owner provides at issuance must
keep each nomin at least twice overcollateralised.
The owner may also destroy nomins in the pool, which is potential avenue
by which to maintain healthy collateralisation levels, as it reduces
supply without withdrawing ether collateral.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once per
fee period.
Ether price is continually updated by an external oracle, and the value
of the backing is computed on this basis. To ensure the integrity of
this system, if the contract's price has not been updated recently enough,
it will temporarily disable itself until it receives more price information.
The contract owner may at any time initiate contract liquidation.
During the liquidation period, most contract functions will be deactivated.
No new nomins may be issued or bought, but users may sell nomins back
to the system.
If the system's collateral falls below a specified level, then anyone
may initiate liquidation.
After the liquidation period has elapsed, which is initially 90 days,
the owner may destroy the contract, transferring any remaining collateral
to a nominated beneficiary address.
This liquidation period may be extended up to a maximum of 180 days.
If the contract is recollateralised, the owner may terminate liquidation.
-----------------------------------------------------------------
*/
contract EtherNomin is ExternStateProxyFeeToken {
/* ========== STATE VARIABLES ========== */
// The oracle provides price information to this contract.
// It may only call the updatePrice() function.
address public oracle;
// The address of the contract which manages confiscation votes.
Court public court;
// Foundation wallet for funds to go to post liquidation.
address public beneficiary;
// Nomins in the pool ready to be sold.
uint public nominPool;
// Impose a 50 basis-point fee for buying from and selling to the nomin pool.
uint public poolFeeRate = UNIT / 200;
// The minimum purchasable quantity of nomins is 1 cent.
uint constant MINIMUM_PURCHASE = UNIT / 100;
// When issuing, nomins must be overcollateralised by this ratio.
uint constant MINIMUM_ISSUANCE_RATIO = 2 * UNIT;
// If the collateralisation ratio of the contract falls below this level,
// immediately begin liquidation.
uint constant AUTO_LIQUIDATION_RATIO = UNIT;
// The liquidation period is the duration that must pass before the liquidation period is complete.
// It can be extended up to a given duration.
uint constant DEFAULT_LIQUIDATION_PERIOD = 90 days;
uint constant MAX_LIQUIDATION_PERIOD = 180 days;
uint public liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
// The timestamp when liquidation was activated. We initialise this to
// uint max, so that we know that we are under liquidation if the
// liquidation timestamp is in the past.
uint public liquidationTimestamp = ~uint(0);
// Ether price from oracle (fiat per ether).
uint public etherPrice;
// Last time the price was updated.
uint public lastPriceUpdate;
// The period it takes for the price to be considered stale.
// If the price is stale, functions that require the price are disabled.
uint public stalePeriod = 2 days;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
/* ========== CONSTRUCTOR ========== */
function EtherNomin(address _havven, address _oracle,
address _beneficiary,
uint initialEtherPrice,
address _owner, TokenState initialState)
ExternStateProxyFeeToken("Ether-Backed USD Nomins", "eUSD",
15 * UNIT / 10000, // nomin transfers incur a 15 bp fee
_havven, // the havven contract is the fee authority
initialState,
_owner)
public
{
oracle = _oracle;
beneficiary = _beneficiary;
etherPrice = initialEtherPrice;
lastPriceUpdate = now;
emit PriceUpdated(etherPrice);
// It should not be possible to transfer to the nomin contract itself.
frozen[this] = true;
}
/* ========== SETTERS ========== */
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emit OracleUpdated(_oracle);
}
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emit CourtUpdated(_court);
}
function setBeneficiary(address _beneficiary)
external
optionalProxy_onlyOwner
{
beneficiary = _beneficiary;
emit BeneficiaryUpdated(_beneficiary);
}
function setPoolFeeRate(uint _poolFeeRate)
external
optionalProxy_onlyOwner
{
require(_poolFeeRate <= UNIT);
poolFeeRate = _poolFeeRate;
emit PoolFeeRateUpdated(_poolFeeRate);
}
function setStalePeriod(uint _stalePeriod)
external
optionalProxy_onlyOwner
{
stalePeriod = _stalePeriod;
emit StalePeriodUpdated(_stalePeriod);
}
/* ========== VIEW FUNCTIONS ========== */
/* Return the equivalent fiat value of the given quantity
* of ether at the current price.
* Reverts if the price is stale. */
function fiatValue(uint eth)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(eth, etherPrice);
}
/* Return the current fiat value of the contract's balance.
* Reverts if the price is stale. */
function fiatBalance()
public
view
returns (uint)
{
// Price staleness check occurs inside the call to fiatValue.
return fiatValue(address(this).balance);
}
/* Return the equivalent ether value of the given quantity
* of fiat at the current price.
* Reverts if the price is stale. */
function etherValue(uint fiat)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* The same as etherValue(), but without the stale price check. */
function etherValueAllowStale(uint fiat)
internal
view
returns (uint)
{
return safeDiv_dec(fiat, etherPrice);
}
/* Return the units of fiat per nomin in the supply.
* Reverts if the price is stale. */
function collateralisationRatio()
public
view
returns (uint)
{
return safeDiv_dec(fiatBalance(), _nominCap());
}
/* Return the maximum number of extant nomins,
* equal to the nomin pool plus total (circulating) supply. */
function _nominCap()
internal
view
returns (uint)
{
return safeAdd(nominPool, totalSupply);
}
/* Return the fee charged on a purchase or sale of n nomins. */
function poolFeeIncurred(uint n)
public
view
returns (uint)
{
return safeMul_dec(n, poolFeeRate);
}
/* Return the fiat cost (including fee) of purchasing n nomins.
* Nomins are purchased for $1, plus the fee. */
function purchaseCostFiat(uint n)
public
view
returns (uint)
{
return safeAdd(n, poolFeeIncurred(n));
}
/* Return the ether cost (including fee) of purchasing n nomins.
* Reverts if the price is stale. */
function purchaseCostEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(purchaseCostFiat(n));
}
/* Return the fiat proceeds (less the fee) of selling n nomins.
* Nomins are sold for $1, minus the fee. */
function saleProceedsFiat(uint n)
public
view
returns (uint)
{
return safeSub(n, poolFeeIncurred(n));
}
/* Return the ether proceeds (less the fee) of selling n
* nomins.
* Reverts if the price is stale. */
function saleProceedsEther(uint n)
public
view
returns (uint)
{
// Price staleness check occurs inside the call to etherValue.
return etherValue(saleProceedsFiat(n));
}
/* The same as saleProceedsEther(), but without the stale price check. */
function saleProceedsEtherAllowStale(uint n)
internal
view
returns (uint)
{
return etherValueAllowStale(saleProceedsFiat(n));
}
/* True iff the current block timestamp is later than the time
* the price was last updated, plus the stale period. */
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdate, stalePeriod) < now;
}
function isLiquidating()
public
view
returns (bool)
{
return liquidationTimestamp <= now;
}
/* True if the contract is self-destructible.
* This is true if either the complete liquidation period has elapsed,
* or if all tokens have been returned to the contract and it has been
* in liquidation for at least a week.
* Since the contract is only destructible after the liquidationTimestamp,
* a fortiori canSelfDestruct() implies isLiquidating(). */
function canSelfDestruct()
public
view
returns (bool)
{
// Not being in liquidation implies the timestamp is uint max, so it would roll over.
// We need to check whether we're in liquidation first.
if (isLiquidating()) {
// These timestamps and durations have values clamped within reasonable values and
// cannot overflow.
bool totalPeriodElapsed = liquidationTimestamp + liquidationPeriod < now;
// Total supply of 0 means all tokens have returned to the pool.
bool allTokensReturned = (liquidationTimestamp + 1 weeks < now) && (totalSupply == 0);
return totalPeriodElapsed || allTokensReturned;
}
return false;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
/* Update the current ether price and update the last updated time,
* refreshing the price staleness.
* Also checks whether the contract's collateral levels have fallen to low,
* and initiates liquidation if that is the case.
* Exceptional conditions:
* Not called by the oracle.
* Not the most recently sent price. */
function updatePrice(uint price, uint timeSent)
external
postCheckAutoLiquidate
{
// Should be callable only by the oracle.
require(msg.sender == oracle);
// Must be the most recently sent price, but not too far in the future.
// (so we can't lock ourselves out of updating the oracle for longer than this)
require(lastPriceUpdate < timeSent && timeSent < now + 10 minutes);
etherPrice = price;
lastPriceUpdate = timeSent;
emit PriceUpdated(price);
}
/* Issues n nomins into the pool available to be bought by users.
* Must be accompanied by $n worth of ether.
* Exceptional conditions:
* Not called by contract owner.
* Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).
* Price is stale. */
function replenishPool(uint n)
external
payable
notLiquidating
optionalProxy_onlyOwner
{
// Price staleness check occurs inside the call to fiatBalance.
// Safe additions are unnecessary here, as either the addition is checked on the following line
// or the overflow would cause the requirement not to be satisfied.
require(fiatBalance() >= safeMul_dec(safeAdd(_nominCap(), n), MINIMUM_ISSUANCE_RATIO));
nominPool = safeAdd(nominPool, n);
emit PoolReplenished(n, msg.value);
}
/* Burns n nomins from the pool.
* Exceptional conditions:
* Not called by contract owner.
* There are fewer than n nomins in the pool. */
function diminishPool(uint n)
external
optionalProxy_onlyOwner
{
// Require that there are enough nomins in the accessible pool to burn
require(nominPool >= n);
nominPool = safeSub(nominPool, n);
emit PoolDiminished(n);
}
/* Sends n nomins to the sender from the pool, in exchange for
* $n plus the fee worth of ether.
* Exceptional conditions:
* Insufficient or too many funds provided.
* More nomins requested than are in the pool.
* n below the purchase minimum (1 cent).
* contract in liquidation.
* Price is stale. */
function buy(uint n)
external
payable
notLiquidating
optionalProxy
{
// Price staleness check occurs inside the call to purchaseEtherCost.
require(n >= MINIMUM_PURCHASE &&
msg.value == purchaseCostEther(n));
address sender = messageSender;
// sub requires that nominPool >= n
nominPool = safeSub(nominPool, n);
state.setBalanceOf(sender, safeAdd(state.balanceOf(sender), n));
emit Purchased(sender, sender, n, msg.value);
emit Transfer(0, sender, n);
totalSupply = safeAdd(totalSupply, n);
}
/* Sends n nomins to the pool from the sender, in exchange for
* $n minus the fee worth of ether.
* Exceptional conditions:
* Insufficient nomins in sender's wallet.
* Insufficient funds in the pool to pay sender.
* Price is stale if not in liquidation. */
function sell(uint n)
external
optionalProxy
{
// Price staleness check occurs inside the call to saleProceedsEther,
// but we allow people to sell their nomins back to the system
// if we're in liquidation, regardless.
uint proceeds;
if (isLiquidating()) {
proceeds = saleProceedsEtherAllowStale(n);
} else {
proceeds = saleProceedsEther(n);
}
require(address(this).balance >= proceeds);
address sender = messageSender;
// sub requires that the balance is greater than n
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), n));
nominPool = safeAdd(nominPool, n);
emit Sold(sender, sender, n, proceeds);
emit Transfer(sender, 0, n);
totalSupply = safeSub(totalSupply, n);
sender.transfer(proceeds);
}
/* Lock nomin purchase function in preparation for destroying the contract.
* While the contract is under liquidation, users may sell nomins back to the system.
* After liquidation period has terminated, the contract may be self-destructed,
* returning all remaining ether to the beneficiary address.
* Exceptional cases:
* Not called by contract owner;
* contract already in liquidation; */
function forceLiquidation()
external
notLiquidating
optionalProxy_onlyOwner
{
beginLiquidation();
}
function beginLiquidation()
internal
{
liquidationTimestamp = now;
emit LiquidationBegun(liquidationPeriod);
}
/* If the contract is liquidating, the owner may extend the liquidation period.
* It may only get longer, not shorter, and it may not be extended past
* the liquidation max. */
function extendLiquidationPeriod(uint extension)
external
optionalProxy_onlyOwner
{
require(isLiquidating());
uint sum = safeAdd(liquidationPeriod, extension);
require(sum <= MAX_LIQUIDATION_PERIOD);
liquidationPeriod = sum;
emit LiquidationExtended(extension);
}
/* Liquidation can only be stopped if the collateralisation ratio
* of this contract has recovered above the automatic liquidation
* threshold, for example if the ether price has increased,
* or by including enough ether in this transaction. */
function terminateLiquidation()
external
payable
priceNotStale
optionalProxy_onlyOwner
{
require(isLiquidating());
require(_nominCap() == 0 || collateralisationRatio() >= AUTO_LIQUIDATION_RATIO);
liquidationTimestamp = ~uint(0);
liquidationPeriod = DEFAULT_LIQUIDATION_PERIOD;
emit LiquidationTerminated();
}
/* The owner may destroy this contract, returning all funds back to the beneficiary
* wallet, may only be called after the contract has been in
* liquidation for at least liquidationPeriod, or all circulating
* nomins have been sold back into the pool. */
function selfDestruct()
external
optionalProxy_onlyOwner
{
require(canSelfDestruct());
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function confiscateBalance(address target)
external
{
// Should be callable only by the confiscation court.
require(Court(msg.sender) == court);
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
// I leave them in out of paranoia.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = state.balanceOf(target);
state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), balance));
state.setBalanceOf(target, 0);
frozen[target] = true;
emit AccountFrozen(target, target, balance);
emit Transfer(target, address(this), balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
if (frozen[target] && EtherNomin(target) != this) {
frozen[target] = false;
emit AccountUnfrozen(target, target);
}
}
/* Fallback function allows convenient collateralisation of the contract,
* including by non-foundation parties. */
function() public payable {}
/* ========== MODIFIERS ========== */
modifier notLiquidating
{
require(!isLiquidating());
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* Any function modified by this will automatically liquidate
* the system if the collateral levels are too low.
* This is called on collateral-value/nomin-supply modifying functions that can
* actually move the contract into liquidation. This is really only
* the price update, since issuance requires that the contract is overcollateralised,
* burning can only destroy tokens without withdrawing backing, buying from the pool can only
* asymptote to a collateralisation level of unity, while selling into the pool can only
* increase the collateralisation ratio.
* Additionally, price update checks should/will occur frequently. */
modifier postCheckAutoLiquidate
{
_;
if (!isLiquidating() && _nominCap() != 0 && collateralisationRatio() < AUTO_LIQUIDATION_RATIO) {
beginLiquidation();
}
}
/* ========== EVENTS ========== */
event PoolReplenished(uint nominsCreated, uint collateralDeposited);
event PoolDiminished(uint nominsDestroyed);
event Purchased(address buyer, address indexed buyerIndex, uint nomins, uint eth);
event Sold(address seller, address indexed sellerIndex, uint nomins, uint eth);
event PriceUpdated(uint newPrice);
event StalePeriodUpdated(uint newPeriod);
event OracleUpdated(address newOracle);
event CourtUpdated(address newCourt);
event BeneficiaryUpdated(address newBeneficiary);
event LiquidationBegun(uint duration);
event LiquidationTerminated();
event LiquidationExtended(uint extension);
event PoolFeeRateUpdated(uint newFeeRate);
event SelfDestructed(address beneficiary);
event AccountFrozen(address target, address indexed targetIndex, uint balance);
event AccountUnfrozen(address target, address indexed targetIndex);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A token interface to be overridden to produce an ERC20-compliant
token contract. It relies on being called underneath a proxy,
as described in Proxy.sol.
This contract utilises a state for upgradability purposes.
-----------------------------------------------------------------
*/
contract ExternStateProxyToken is SafeDecimalMath, Proxyable {
/* ========== STATE VARIABLES ========== */
// Stores balances and allowances.
TokenState public state;
// Other ERC20 fields
string public name;
string public symbol;
uint public totalSupply;
/* ========== CONSTRUCTOR ========== */
function ExternStateProxyToken(string _name, string _symbol,
uint initialSupply, address initialBeneficiary,
TokenState _state, address _owner)
Proxyable(_owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = initialSupply;
// if the state isn't set, create a new one
if (_state == TokenState(0)) {
state = new TokenState(_owner, address(this));
state.setBalanceOf(initialBeneficiary, totalSupply);
emit Transfer(address(0), initialBeneficiary, initialSupply);
} else {
state = _state;
}
}
/* ========== VIEWS ========== */
function allowance(address tokenOwner, address spender)
public
view
returns (uint)
{
return state.allowance(tokenOwner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return state.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function setState(TokenState _state)
external
optionalProxy_onlyOwner
{
state = _state;
emit StateUpdated(_state);
}
/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), value));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
emit Transfer(sender, to, value);
return true;
}
/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
require(from != address(0) && to != address(0));
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(from, safeSub(state.balanceOf(from), value));
state.setAllowance(from, sender, safeSub(state.allowance(from, sender), value));
state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint value)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
state.setAllowance(sender, spender, value);
emit Approval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event StateUpdated(address newState);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
contract HavvenEscrow is Owned, LimitedSetup(8 weeks), SafeDecimalMath {
// The corresponding Havven contract.
Havven public havven;
// Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
// These are the times at which each given quantity of havvens vests.
mapping(address => uint[2][]) public vestingSchedules;
// An account's total vested havven balance to save recomputing this for fee extraction purposes.
mapping(address => uint) public totalVestedAccountBalance;
// The total remaining vested balance, for verifying the actual havven balance of this contract against.
uint public totalVestedBalance;
/* ========== CONSTRUCTOR ========== */
function HavvenEscrow(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/* A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/* The number of vesting dates in an account's schedule. */
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/* Get a particular schedule entry for an account.
* The return value is a pair (timestamp, havven quantity) */
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/* Get the time at which a given schedule entry will vest. */
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return vestingSchedules[account][index][0];
}
/* Get the quantity of havvens associated with a given schedule entry. */
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return vestingSchedules[account][index][1];
}
/* Obtain the index of the next schedule entry that will vest for a given user. */
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/* Obtain the next schedule entry that will vest for a given user.
* The return value is a pair (timestamp, havven quantity) */
function getNextVestingEntry(address account)
external
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/* Obtain the time at which the next schedule entry will vest for a given user. */
function getNextVestingTime(address account)
external
view
returns (uint)
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return 0;
}
return getVestingTime(account, index);
}
/* Obtain the quantity which the next schedule entry will vest for a given user. */
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return 0;
}
return getVestingQuantity(account, index);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Withdraws a quantity of havvens back to the havven contract. */
function withdrawHavvens(uint quantity)
external
onlyOwner
setupFunction
{
havven.transfer(havven, quantity);
}
/* Destroy the vesting information associated with an account. */
function purgeAccount(address account)
external
onlyOwner
setupFunction
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/* Add a new vesting entry at a given time and quantity to an account's schedule.
* A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists. */
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
setupFunction
{
// No empty or already-passed vesting entries allowed.
require(now < time);
require(quantity != 0);
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this));
if (vestingSchedules[account].length == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
// Disallow adding new vested havvens earlier than the last one.
// Since entries are only appended, this means that no vesting date can be repeated.
require(getVestingTime(account, numVestingEntries(account) - 1) < time);
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/* Construct a vesting schedule to release a quantities of havvens
* over a series of intervals. Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing. */
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
setupFunction
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/* Allow a user to withdraw any tokens that have vested. */
function vest()
external
{
uint total;
for (uint i = 0; i < numVestingEntries(msg.sender); i++) {
uint time = getVestingTime(msg.sender, i);
// The list is sorted; when we reach the first future time, bail out.
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, msg.sender,
now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address beneficiary, address indexed beneficiaryIndex, uint time, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind.
-----------------------------------------------------------------
*/
contract SelfDestructible is Owned {
uint public initiationTime = ~uint(0);
uint constant SD_DURATION = 3 days;
address public beneficiary;
function SelfDestructible(address _owner, address _beneficiary)
public
Owned(_owner)
{
beneficiary = _beneficiary;
}
function setBeneficiary(address _beneficiary)
external
onlyOwner
{
beneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
emit SelfDestructInitiated(SD_DURATION);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = ~uint(0);
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(initiationTime + SD_DURATION < now);
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
event SelfDestructInitiated(uint duration);
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens is entitled to a share in the fees levied on
nomin transactions, and additionally may participate in nomin
confiscation votes.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins.
Thus an account may only withdraw the fees owed to them for the previous
period, and may only do so once per period.
Any unclaimed fees roll over into the common pot for the next period.
The fee entitlement of a havven holder is proportional to their average
havven balance over the last fee period. This is computed by measuring the
area under the graph of a user's balance over time, and then when fees are
distributed, dividing through by the duration of the fee period.
We need only update fee entitlement on transfer when the havven balances of the sender
and recipient are modified. This is for efficiency, and adds an implicit friction to
trading in the havven market. A havven holder pays for his own recomputation whenever
he wants to change his position, which saves the foundation having to maintain a pot
dedicated to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to p
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
Additionally, we keep track also of the penultimate and not just the last
average balance, in order to support the voting functionality detailed in Court.sol.
-----------------------------------------------------------------
*/
contract Havven is ExternStateProxyToken, SelfDestructible {
/* ========== STATE VARIABLES ========== */
// Sums of balances*duration in the current fee period.
// range: decimals; units: havven-seconds
mapping(address => uint) public currentBalanceSum;
// Average account balances in the last completed fee period. This is proportional
// to that account's last period fee entitlement.
// (i.e. currentBalanceSum for the previous period divided through by duration)
// WARNING: This may not have been updated for the latest fee period at the
// time it is queried.
// range: decimals; units: havvens
mapping(address => uint) public lastAverageBalance;
// The average account balances in the period before the last completed fee period.
// This is used as a person's weight in a confiscation vote, so it implies that
// the vote duration must be no longer than the fee period in order to guarantee that
// no portion of a fee period used for determining vote weights falls within the
// duration of a vote it contributes to.
// WARNING: This may not have been updated for the latest fee period at the
// time it is queried.
mapping(address => uint) public penultimateAverageBalance;
// The time an account last made a transfer.
// range: naturals
mapping(address => uint) public lastTransferTimestamp;
// The time the current fee period began.
uint public feePeriodStartTime = 3;
// The actual start of the last fee period (seconds).
// This, and the penultimate fee period can be initially set to any value
// 0 < val < now, as everyone's individual lastTransferTime will be 0
// and as such, their lastAvgBal/penultimateAvgBal will be set to that value
// apart from the contract, which will have totalSupply
uint public lastFeePeriodStartTime = 2;
// The actual start of the penultimate fee period (seconds).
uint public penultimateFeePeriodStartTime = 1;
// Fee periods will roll over in no shorter a time than this.
uint public targetFeePeriodDurationSeconds = 4 weeks;
// And may not be set to be shorter than a day.
uint constant MIN_FEE_PERIOD_DURATION_SECONDS = 1 days;
// And may not be set to be longer than six months.
uint constant MAX_FEE_PERIOD_DURATION_SECONDS = 26 weeks;
// The quantity of nomins that were in the fee pot at the time
// of the last fee rollover (feePeriodStartTime).
uint public lastFeesCollected;
mapping(address => bool) public hasWithdrawnLastPeriodFees;
EtherNomin public nomin;
HavvenEscrow public escrow;
/* ========== CONSTRUCTOR ========== */
function Havven(TokenState initialState, address _owner)
ExternStateProxyToken("Havven", "HAV", 1e8 * UNIT, address(this), initialState, _owner)
SelfDestructible(_owner, _owner)
// Owned is initialised in ExternStateProxyToken
public
{
lastTransferTimestamp[this] = now;
feePeriodStartTime = now;
lastFeePeriodStartTime = now - targetFeePeriodDurationSeconds;
penultimateFeePeriodStartTime = now - 2*targetFeePeriodDurationSeconds;
}
/* ========== SETTERS ========== */
function setNomin(EtherNomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
}
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
}
function setTargetFeePeriodDuration(uint duration)
external
postCheckFeePeriodRollover
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION_SECONDS <= duration &&
duration <= MAX_FEE_PERIOD_DURATION_SECONDS);
targetFeePeriodDurationSeconds = duration;
emit FeePeriodDurationUpdated(duration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Allow the owner of this contract to endow any address with havvens
* from the initial supply. Since the entire initial supply resides
* in the havven contract, this disallows the foundation from withdrawing
* fees on undistributed balances. This function can also be used
* to retrieve any havvens sent to the Havven contract itself. */
function endow(address account, uint value)
external
optionalProxy_onlyOwner
returns (bool)
{
// Use "this" in order that the havven account is the sender.
// That this is an explicit transfer also initialises fee entitlement information.
return _transfer(this, account, value);
}
/* Allow the owner of this contract to emit transfer events for
* contract setup purposes. */
function emitTransferEvents(address sender, address[] recipients, uint[] values)
external
onlyOwner
{
for (uint i = 0; i < recipients.length; ++i) {
emit Transfer(sender, recipients[i], values[i]);
}
}
/* Override ERC20 transfer function in order to perform
* fee entitlement recomputation whenever balances are updated. */
function transfer(address to, uint value)
external
optionalProxy
returns (bool)
{
return _transfer(messageSender, to, value);
}
/* Anything calling this must apply the optionalProxy or onlyProxy modifier. */
function _transfer(address sender, address to, uint value)
internal
preCheckFeePeriodRollover
returns (bool)
{
uint senderPreBalance = state.balanceOf(sender);
uint recipientPreBalance = state.balanceOf(to);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
_transfer_byProxy(sender, to, value);
// Zero-value transfers still update fee entitlement information,
// and may roll over the fee period.
adjustFeeEntitlement(sender, senderPreBalance);
adjustFeeEntitlement(to, recipientPreBalance);
return true;
}
/* Override ERC20 transferFrom function in order to perform
* fee entitlement recomputation whenever balances are updated. */
function transferFrom(address from, address to, uint value)
external
preCheckFeePeriodRollover
optionalProxy
returns (bool)
{
uint senderPreBalance = state.balanceOf(from);
uint recipientPreBalance = state.balanceOf(to);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
_transferFrom_byProxy(messageSender, from, to, value);
// Zero-value transfers still update fee entitlement information,
// and may roll over the fee period.
adjustFeeEntitlement(from, senderPreBalance);
adjustFeeEntitlement(to, recipientPreBalance);
return true;
}
/* Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account. */
function withdrawFeeEntitlement()
public
preCheckFeePeriodRollover
optionalProxy
{
address sender = messageSender;
// Do not deposit fees into frozen accounts.
require(!nomin.frozen(sender));
// check the period has rolled over first
rolloverFee(sender, lastTransferTimestamp[sender], state.balanceOf(sender));
// Only allow accounts to withdraw fees once per period.
require(!hasWithdrawnLastPeriodFees[sender]);
uint feesOwed;
if (escrow != HavvenEscrow(0)) {
feesOwed = escrow.totalVestedAccountBalance(sender);
}
feesOwed = safeDiv_dec(safeMul_dec(safeAdd(feesOwed, lastAverageBalance[sender]),
lastFeesCollected),
totalSupply);
hasWithdrawnLastPeriodFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFee(sender, feesOwed);
emit FeesWithdrawn(sender, sender, feesOwed);
}
}
/* Update the fee entitlement since the last transfer or entitlement
* adjustment. Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call. */
function adjustFeeEntitlement(address account, uint preBalance)
internal
{
// The time since the last transfer clamps at the last fee rollover time if the last transfer
// was earlier than that.
rolloverFee(account, lastTransferTimestamp[account], preBalance);
currentBalanceSum[account] = safeAdd(
currentBalanceSum[account],
safeMul(preBalance, now - lastTransferTimestamp[account])
);
// Update the last time this user's balance changed.
lastTransferTimestamp[account] = now;
}
/* Update the given account's previous period fee entitlement value.
* Do nothing if the last transfer occurred since the fee period rolled over.
* If the entitlement was updated, also update the last transfer time to be
* at the timestamp of the rollover, so if this should do nothing if called more
* than once during a given period.
*
* Consider the case where the entitlement is updated. If the last transfer
* occurred at time t in the last period, then the starred region is added to the
* entitlement, the last transfer timestamp is moved to r, and the fee period is
* rolled over from k-1 to k so that the new fee period start time is at time r.
*
* k-1 | k
* s __|
* _ _ ___|**|
* |**|
* _ _ ___|**|___ __ _ _
* |
* t |
* r
*
* Similar computations are performed according to the fee period in which the
* last transfer occurred.
*/
function rolloverFee(address account, uint lastTransferTime, uint preBalance)
internal
{
if (lastTransferTime < feePeriodStartTime) {
if (lastTransferTime < lastFeePeriodStartTime) {
// The last transfer predated the previous two fee periods.
if (lastTransferTime < penultimateFeePeriodStartTime) {
// The balance did nothing in the penultimate fee period, so the average balance
// in this period is their pre-transfer balance.
penultimateAverageBalance[account] = preBalance;
// The last transfer occurred within the one-before-the-last fee period.
} else {
// No overflow risk here: the failed guard implies (penultimateFeePeriodStartTime <= lastTransferTime).
penultimateAverageBalance[account] = safeDiv(
safeAdd(currentBalanceSum[account], safeMul(preBalance, (lastFeePeriodStartTime - lastTransferTime))),
(lastFeePeriodStartTime - penultimateFeePeriodStartTime)
);
}
// The balance did nothing in the last fee period, so the average balance
// in this period is their pre-transfer balance.
lastAverageBalance[account] = preBalance;
// The last transfer occurred within the last fee period.
} else {
// The previously-last average balance becomes the penultimate balance.
penultimateAverageBalance[account] = lastAverageBalance[account];
// No overflow risk here: the failed guard implies (lastFeePeriodStartTime <= lastTransferTime).
lastAverageBalance[account] = safeDiv(
safeAdd(currentBalanceSum[account], safeMul(preBalance, (feePeriodStartTime - lastTransferTime))),
(feePeriodStartTime - lastFeePeriodStartTime)
);
}
// Roll over to the next fee period.
currentBalanceSum[account] = 0;
hasWithdrawnLastPeriodFees[account] = false;
lastTransferTimestamp[account] = feePeriodStartTime;
}
}
/* Recompute and return the given account's average balance information.
* This also rolls over the fee period if necessary, and brings
* the account's current balance sum up to date. */
function _recomputeAccountLastAverageBalance(address account)
internal
preCheckFeePeriodRollover
returns (uint)
{
adjustFeeEntitlement(account, state.balanceOf(account));
return lastAverageBalance[account];
}
/* Recompute and return the sender's average balance information. */
function recomputeLastAverageBalance()
external
optionalProxy
returns (uint)
{
return _recomputeAccountLastAverageBalance(messageSender);
}
/* Recompute and return the given account's average balance information. */
function recomputeAccountLastAverageBalance(address account)
external
returns (uint)
{
return _recomputeAccountLastAverageBalance(account);
}
function rolloverFeePeriod()
public
{
checkFeePeriodRollover();
}
/* ========== MODIFIERS ========== */
/* If the fee period has rolled over, then
* save the start times of the last fee period,
* as well as the penultimate fee period.
*/
function checkFeePeriodRollover()
internal
{
// If the fee period has rolled over...
if (feePeriodStartTime + targetFeePeriodDurationSeconds <= now) {
lastFeesCollected = nomin.feePool();
// Shift the three period start times back one place
penultimateFeePeriodStartTime = lastFeePeriodStartTime;
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emit FeePeriodRollover(now);
}
}
modifier postCheckFeePeriodRollover
{
_;
checkFeePeriodRollover();
}
modifier preCheckFeePeriodRollover
{
checkFeePeriodRollover();
_;
}
/* ========== EVENTS ========== */
event FeePeriodRollover(uint timestamp);
event FeePeriodDurationUpdated(uint duration);
event FeesWithdrawn(address account, address indexed accountIndex, uint value);
}
/*
-----------------------------------------------------------------
CONTRACT DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and EtherNomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract TokenState is Owned {
// the address of the contract that can modify balances and allowances
// this can only be changed by the owner of this contract
address public associatedContract;
// ERC20 fields.
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function TokenState(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address _associatedContract);
}
/*
MIT License
Copyright (c) 2018 Havven
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
|
True iff subtracting y from x will not overflow in the negative direction. /
|
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
| 1,229,996 |
./partial_match/1/0xa76EA705783b595b420bb36F196540a2Ed629673/sources/MatchingMarket.sol
|
Ugly hack to work around rounding errors. Based on the idea that the furthest the amounts can stray from their "true" values is 1. Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from their "correct" values and m_buy_amt and t_buy_amt at -1. Since (c - 1) (d - 1) > (a + 1) (b + 1) is equivalent to c d > a b + a + b + c + d, we write...
|
function _matcho(uint t_pay_amt, ERC20 t_pay_gem,
while (_best[address(t_buy_gem)][address(t_pay_gem)] > 0) {
best_maker_id = _best[address(t_buy_gem)][address(t_pay_gem)];
m_buy_amt = offers[best_maker_id].buy_amt;
m_pay_amt = offers[best_maker_id].pay_amt;
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) +
(rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0))
{
break;
}
t_buy_amt_old = t_buy_amt;
t_buy_amt = sub(t_buy_amt, min(m_pay_amt, t_buy_amt));
t_pay_amt = mul(t_buy_amt, t_pay_amt) / t_buy_amt_old;
if (t_pay_amt == 0 || t_buy_amt == 0) {
break;
}
}
| 3,575,061 |
./full_match/80001/0x55804061c6a38bde6c48f8320a50D599AFc1a874/sources/contracts/Cards.sol
|
Obtém a lista de tokens elegíveis Verifica se o usuário possui um dos tokens elegíveis
|
function claimSpecial() external {
uint256[] memory tokenIds = getEligibleTokenIds();
bool hasEligibleToken = false;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (balanceOf[msg.sender] [tokenIds[i]] > 0) {
hasEligibleToken = true;
break;
}
}
_mint(msg.sender, 0, 1, "");
}
| 9,526,138 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
//
/**
* @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);
}
//
/**
* @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;
}
}
//
/**
* @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 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);
}
}
}
}
//
/**
* @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");
}
}
}
//
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract WarmupTeamLock {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(uint256 amount);
IERC20 public token;
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public start;
uint256 public duration;
uint256 public released;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param _token ERC20 token which is being vested
* @param _beneficiary ERC20 token which is being vested
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
*/
constructor(
uint256 _token,
address _beneficiary,
uint256 _start,
uint256 _duration
)
public
{
require(_duration > 0);
require(_start.add(_duration) > block.timestamp);
token = IERC20(_token);
beneficiary = _beneficiary;
duration = _duration;
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
uint256 unreleased = _releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit TokensReleased(unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function _releasableAmount() private view returns (uint256) {
return _vestedAmount().sub(released);
}
/**
* @dev Calculates the amount that has already vested.
*/
function _vestedAmount() private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released);
if (block.timestamp >= start.add(duration)) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
|
Calculates the amount that has already vested./
|
function _vestedAmount() private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released);
if (block.timestamp >= start.add(duration)) {
return totalBalance;
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
| 10,649,152 |
pragma solidity ^0.5.4;
library Counters {
using SafeMath for uint256;
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
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);
}
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;
}
}
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;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_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;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply = 1e6;
constructor() public {
_balances[msg.sender] = 1e6;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @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 Transfer token to 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) {
_transfer(msg.sender, 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) {
_approve(msg.sender, spender, value);
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 returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @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, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
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;
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 => Counters.Counter) 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)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_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].current();
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return 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));
_transferFrom(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 {
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 bool 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 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
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
require(!_exists(tokenId));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @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].decrement();
_ownedTokensCount[to].increment();
_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 bool 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);
}
}
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
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) external view returns (string memory) {
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 memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead
* @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];
}
}
}
contract OathForge is ERC721, ERC721Metadata, Ownable {
using SafeMath for uint256;
uint256 private _totalSupply;
uint256 private _nextTokenId;
mapping(uint256 => uint256) private _sunsetInitiatedAt;
mapping(uint256 => uint256) private _sunsetLength;
mapping(uint256 => uint256) private _redemptionCodeHashSubmittedAt;
mapping(uint256 => bytes32) private _redemptionCodeHash;
mapping(address => bool) private _isBlacklisted;
/// @param name The ERC721 Metadata name
/// @param symbol The ERC721 Metadata symbol
constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
/// @dev Emits when a sunset has been initiated
/// @param tokenId The token id
event SunsetInitiated(uint256 indexed tokenId);
/// @dev Emits when a redemption code hash has been submitted
/// @param tokenId The token id
/// @param redemptionCodeHash The redemption code hash
event RedemptionCodeHashSubmitted(uint256 indexed tokenId, bytes32 redemptionCodeHash);
/// @dev Returns the total number of tokens (minted - burned) registered
function totalSupply() external view returns(uint256){
return _totalSupply;
}
/// @dev Returns the token id of the next minted token
function nextTokenId() external view returns(uint256){
return _nextTokenId;
}
/// @dev Returns if an address is blacklisted
/// @param to The address to check
function isBlacklisted(address to) external view returns(bool){
return _isBlacklisted[to];
}
/// @dev Returns the timestamp at which a token's sunset was initated. Returns 0 if no sunset has been initated.
/// @param tokenId The token id
function sunsetInitiatedAt(uint256 tokenId) external view returns(uint256){
return _sunsetInitiatedAt[tokenId];
}
/// @dev Returns the sunset length of a token
/// @param tokenId The token id
function sunsetLength(uint256 tokenId) external view returns(uint256){
return _sunsetLength[tokenId];
}
/// @dev Returns the redemption code hash submitted for a token
/// @param tokenId The token id
function redemptionCodeHash(uint256 tokenId) external view returns(bytes32){
return _redemptionCodeHash[tokenId];
}
/// @dev Returns the timestamp at which a redemption code hash was submitted
/// @param tokenId The token id
function redemptionCodeHashSubmittedAt(uint256 tokenId) external view returns(uint256){
return _redemptionCodeHashSubmittedAt[tokenId];
}
/// @dev Mint a token. Only `owner` may call this function.
/// @param to The receiver of the token
/// @param tokenURI The tokenURI of the the tokenURI
/// @param __sunsetLength The length (in seconds) that a sunset period can last
function mint(address to, string memory tokenURI, uint256 __sunsetLength) public onlyOwner {
_mint(to, _nextTokenId);
_sunsetLength[_nextTokenId] = __sunsetLength;
_setTokenURI(_nextTokenId, tokenURI);
_nextTokenId = _nextTokenId.add(1);
_totalSupply = _totalSupply.add(1);
}
/// @dev Initiate a sunset. Sets `sunsetInitiatedAt` to current timestamp. Only `owner` may call this function.
/// @param tokenId The id of the token
function initiateSunset(uint256 tokenId) external onlyOwner {
require(tokenId < _nextTokenId);
require(_sunsetInitiatedAt[tokenId] == 0);
_sunsetInitiatedAt[tokenId] = now;
emit SunsetInitiated(tokenId);
}
/// @dev Submit a redemption code hash for a specific token. Burns the token. Sets `redemptionCodeHashSubmittedAt` to current timestamp. Decreases `totalSupply` by 1.
/// @param tokenId The id of the token
/// @param __redemptionCodeHash The redemption code hash
function submitRedemptionCodeHash(uint256 tokenId, bytes32 __redemptionCodeHash) external {
_burn(msg.sender, tokenId);
_redemptionCodeHashSubmittedAt[tokenId] = now;
_redemptionCodeHash[tokenId] = __redemptionCodeHash;
_totalSupply = _totalSupply.sub(1);
emit RedemptionCodeHashSubmitted(tokenId, __redemptionCodeHash);
}
/// @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(!_isBlacklisted[to]);
if (_sunsetInitiatedAt[tokenId] > 0) {
require(now <= _sunsetInitiatedAt[tokenId].add(_sunsetLength[tokenId]));
}
super.transferFrom(from, to, tokenId);
}
/**
* @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 {
require(!_isBlacklisted[to]);
super.approve(to, 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(!_isBlacklisted[to]);
super.setApprovalForAll(to, approved);
}
/// @dev Set `tokenUri`. Only `owner` may do this.
/// @param tokenId The id of the token
/// @param tokenURI The token URI
function setTokenURI(uint256 tokenId, string calldata tokenURI) external onlyOwner {
_setTokenURI(tokenId, tokenURI);
}
/// @dev Set if an address is blacklisted
/// @param to The address to change
/// @param __isBlacklisted True if the address should be blacklisted, false otherwise
function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner {
_isBlacklisted[to] = __isBlacklisted;
}
}
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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
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;
}
}
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract RiftPact is ERC20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 private _parentTokenId;
uint256 private _auctionAllowedAt;
address private _currencyAddress;
address private _parentToken;
uint256 private _minAuctionCompleteWait;
uint256 private _minBidDeltaPermille;
uint256 private _auctionStartedAt;
uint256 private _auctionCompletedAt;
uint256 private _minBid = 1;
uint256 private _topBid;
address private _topBidder;
uint256 private _topBidSubmittedAt;
mapping(address => bool) private _isBlacklisted;
/// @param __parentToken The address of the OathForge contract
/// @param __parentTokenId The id of the token on the OathForge contract
/// @param __totalSupply The total supply
/// @param __currencyAddress The address of the currency contract
/// @param __auctionAllowedAt The timestamp at which anyone can start an auction
/// @param __minAuctionCompleteWait The minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed
/// @param __minBidDeltaPermille The minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be
constructor(
address __parentToken,
uint256 __parentTokenId,
uint256 __totalSupply,
address __currencyAddress,
uint256 __auctionAllowedAt,
uint256 __minAuctionCompleteWait,
uint256 __minBidDeltaPermille
) public {
_parentToken = __parentToken;
_parentTokenId = __parentTokenId;
_currencyAddress = __currencyAddress;
_auctionAllowedAt = __auctionAllowedAt;
_minAuctionCompleteWait = __minAuctionCompleteWait;
_minBidDeltaPermille = __minBidDeltaPermille;
_mint(msg.sender, __totalSupply);
}
/// @dev Emits when an auction is started
event AuctionStarted();
/// @dev Emits when the auction is completed
/// @param bid The final bid price of the auction
/// @param winner The winner of the auction
event AuctionCompleted(address winner, uint256 bid);
/// @dev Emits when there is a bid
/// @param bid The bid
/// @param bidder The address of the bidder
event Bid(address bidder, uint256 bid);
/// @dev Emits when there is a payout
/// @param to The address of the account paying out
/// @param balance The balance of `to` prior to the paying out
event Payout(address to, uint256 balance);
/// @dev Returns the OathForge contract address. **UI should check for phishing.**.
function parentToken() external view returns(address) {
return _parentToken;
}
/// @dev Returns the OathForge token id. **Does not imply RiftPact has ownership over token.**
function parentTokenId() external view returns(uint256) {
return _parentTokenId;
}
/// @dev Returns the currency contract address.
function currencyAddress() external view returns(address) {
return _currencyAddress;
}
/// @dev Returns the minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed.
function minAuctionCompleteWait() external view returns(uint256) {
return _minAuctionCompleteWait;
}
/// @dev Returns the minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be
function minBidDeltaPermille() external view returns(uint256) {
return _minBidDeltaPermille;
}
/// @dev Returns the timestamp at which anyone can start an auction by calling [`startAuction()`](#startAuction())
function auctionAllowedAt() external view returns(uint256) {
return _auctionAllowedAt;
}
/// @dev Returns the minimum bid in currency
function minBid() external view returns(uint256) {
return _minBid;
}
/// @dev Returns the timestamp at which an auction was started or 0 if no auction has been started
function auctionStartedAt() external view returns(uint256) {
return _auctionStartedAt;
}
/// @dev Returns the timestamp at which an auction was completed or 0 if no auction has been completed
function auctionCompletedAt() external view returns(uint256) {
return _auctionCompletedAt;
}
/// @dev Returns the top bid or 0 if no bids have been placed
function topBid() external view returns(uint256) {
return _topBid;
}
/// @dev Returns the top bidder or `address(0)` if no bids have been placed
function topBidder() external view returns(address) {
return _topBidder;
}
/// @dev Start an auction
function startAuction() external nonReentrant {
require(_auctionStartedAt == 0);
require(
(now >= _auctionAllowedAt)
|| (OathForge(_parentToken).sunsetInitiatedAt(_parentTokenId) > 0)
);
emit AuctionStarted();
_auctionStartedAt = now;
}
/// @dev Submit a bid. Must have sufficient funds approved in currency contract (bid * totalSupply).
/// @param bid Bid in currency
function submitBid(uint256 bid) external nonReentrant {
require(_auctionStartedAt > 0);
require(_auctionCompletedAt == 0);
require(bid >= _minBid);
emit Bid(msg.sender, bid);
uint256 _totalSupply = totalSupply();
if (_topBidder != address(0)) {
/// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid
/* require(ERC20(_currencyAddress).transfer(_topBidder, _topBid * _totalSupply)); */
require(ERC20(_currencyAddress).transfer(_topBidder, _topBid));
}
/// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid
/* require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid * _totalSupply)); */
require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid));
_topBid = bid;
_topBidder = msg.sender;
_topBidSubmittedAt = now;
/* 3030 * 10 = 30300
delta = 30300 / 1000 = 30,3
30300 % 1000 = 300 > 0, yes
roundUp = 1
minBid = 3030 + 30 + 1 which is wrong, it should be 3060 instead of 3061 */
uint256 minBidNumerator = bid * _minBidDeltaPermille;
uint256 minBidDelta = minBidNumerator / 1000;
uint256 minBidRoundUp = 0;
/// NOTE commented out because it doesn't work as expected with big bids
/* if((bid * _minBidDeltaPermille) % 1000 > 0) {
minBidRoundUp = 1;
} */
if((bid * _minBidDeltaPermille) < 1000) {
minBidRoundUp = 1;
}
_minBid = bid + minBidDelta + minBidRoundUp;
}
/// @dev Complete auction
function completeAuction() external {
require(_auctionCompletedAt == 0);
require(_topBid > 0);
require((_topBidSubmittedAt + _minAuctionCompleteWait) < now);
emit AuctionCompleted(_topBidder, _topBid);
_auctionCompletedAt = now;
}
/// @dev Payout `currency` after auction completed
function payout() external nonReentrant {
uint256 balance = balanceOf(msg.sender);
require(balance > 0);
require(_auctionCompletedAt > 0);
emit Payout(msg.sender, balance);
/// NOTE this won't work since we can't send more tokens than what's already in this contract
/* require(ERC20(_currencyAddress).transfer(msg.sender, balance * _topBid)); */
require(ERC20(_currencyAddress).transfer(msg.sender, _topBid));
/// NOTE Remove this since the sender doesn't have any riftPact tokens inside this contract so we can't burn them.
/* _burn(msg.sender, balance); */
}
/// @dev Returns if an address is blacklisted
/// @param to The address to check
function isBlacklisted(address to) external view returns(bool){
return _isBlacklisted[to];
}
/// @dev Set if an address is blacklisted
/// @param to The address to change
/// @param __isBlacklisted True if the address should be blacklisted, false otherwise
function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner {
_isBlacklisted[to] = __isBlacklisted;
}
/**
* @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(!_isBlacklisted[to]);
return super.transfer(to, value);
}
/**
* @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 returns (bool) {
require(!_isBlacklisted[to]);
return super.transferFrom(from, to, value);
}
/**
* @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) {
if (value > 0) {
require(!_isBlacklisted[spender]);
}
return super.approve(spender, value);
}
/**
* @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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(!_isBlacklisted[spender]);
return super.increaseAllowance(spender, addedValue);
}
}
|
Returns if an address is blacklisted to The address to check
|
function isBlacklisted(address to) external view returns(bool){
return _isBlacklisted[to];
}
}
| 5,390,941 |
pragma solidity ^0.4.21;
/**
* @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 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, 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 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 Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract LittlePhilCoin is MintableToken, PausableToken {
string public name = "Little Phil Coin";
string public symbol = "LPC";
uint8 public decimals = 18;
constructor () public {
// Pause token on creation and only unpause after ICO
pause();
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public {
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract InitialSupplyCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
uint256 public constant decimals = 18;
// Wallet properties
address public companyWallet;
address public teamWallet;
address public projectWallet;
address public advisorWallet;
address public bountyWallet;
address public airdropWallet;
// Team locked tokens
TokenTimelock public teamTimeLock1;
TokenTimelock public teamTimeLock2;
// Reserved tokens
uint256 public constant companyTokens = SafeMath.mul(150000000, (10 ** decimals));
uint256 public constant teamTokens = SafeMath.mul(150000000, (10 ** decimals));
uint256 public constant projectTokens = SafeMath.mul(150000000, (10 ** decimals));
uint256 public constant advisorTokens = SafeMath.mul(100000000, (10 ** decimals));
uint256 public constant bountyTokens = SafeMath.mul(30000000, (10 ** decimals));
uint256 public constant airdropTokens = SafeMath.mul(20000000, (10 ** decimals));
bool private isInitialised = false;
constructor(
address[6] _wallets
) public {
address _companyWallet = _wallets[0];
address _teamWallet = _wallets[1];
address _projectWallet = _wallets[2];
address _advisorWallet = _wallets[3];
address _bountyWallet = _wallets[4];
address _airdropWallet = _wallets[5];
require(_companyWallet != address(0));
require(_teamWallet != address(0));
require(_projectWallet != address(0));
require(_advisorWallet != address(0));
require(_bountyWallet != address(0));
require(_airdropWallet != address(0));
// Set reserved wallets
companyWallet = _companyWallet;
teamWallet = _teamWallet;
projectWallet = _projectWallet;
advisorWallet = _advisorWallet;
bountyWallet = _bountyWallet;
airdropWallet = _airdropWallet;
// Lock team tokens in wallet over time periods
teamTimeLock1 = new TokenTimelock(token, teamWallet, uint64(now + 182 days));
teamTimeLock2 = new TokenTimelock(token, teamWallet, uint64(now + 365 days));
}
/**
* Function: Distribute initial token supply
*/
function setupInitialSupply() internal onlyOwner {
require(isInitialised == false);
uint256 teamTokensSplit = teamTokens.mul(50).div(100);
// Distribute tokens to reserved wallets
LittlePhilCoin(token).mint(companyWallet, companyTokens);
LittlePhilCoin(token).mint(projectWallet, projectTokens);
LittlePhilCoin(token).mint(advisorWallet, advisorTokens);
LittlePhilCoin(token).mint(bountyWallet, bountyTokens);
LittlePhilCoin(token).mint(airdropWallet, airdropTokens);
LittlePhilCoin(token).mint(address(teamTimeLock1), teamTokensSplit);
LittlePhilCoin(token).mint(address(teamTimeLock2), teamTokensSplit);
isInitialised = true;
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title TokenCappedCrowdsale
* @dev Crowdsale with a limit for total minted tokens.
*/
contract TokenCappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public tokenCap = 0;
// Amount of LPC raised
uint256 public tokensRaised = 0;
// event for manual refund of cap overflow
event CapOverflow(address indexed sender, uint256 weiAmount, uint256 receivedTokens, uint256 date);
/**
* Checks whether the tokenCap has been reached.
* @return Whether the tokenCap was reached
*/
function capReached() public view returns (bool) {
return tokensRaised >= tokenCap;
}
/**
* Accumulate the purchased tokens to the total raised
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
super._updatePurchasingState(_beneficiary, _weiAmount);
uint256 purchasedTokens = _getTokenAmount(_weiAmount);
tokensRaised = tokensRaised.add(purchasedTokens);
if(capReached()) {
// manual process unused eth amount to sender
emit CapOverflow(_beneficiary, _weiAmount, purchasedTokens, now);
}
}
}
/**
* @title TieredCrowdsale
* @dev Extension of Crowdsale contract that decreases the number of LPC tokens purchases dependent on the current number of tokens sold.
*/
contract TieredCrowdsale is TokenCappedCrowdsale, Ownable {
using SafeMath for uint256;
/**
SalesState enum for use in state machine to manage sales rates
*/
enum SaleState {
Initial, // All contract initialization calls
PrivateSale, // Private sale for industy and closed group investors
FinalisedPrivateSale, // Close private sale
PreSale, // Pre sale ICO (40% bonus LPC hard-capped at 180 million tokens)
FinalisedPreSale, // Close presale
PublicSaleTier1, // Tier 1 ICO public sale (30% bonus LPC capped at 85 million tokens)
PublicSaleTier2, // Tier 2 ICO public sale (20% bonus LPC capped at 65 million tokens)
PublicSaleTier3, // Tier 3 ICO public sale (10% bonus LPC capped at 45 million tokens)
PublicSaleTier4, // Tier 4 ICO public sale (standard rate capped at 25 million tokens)
FinalisedPublicSale, // Close public sale
Closed // ICO has finished, all tokens must have been claimed
}
SaleState public state = SaleState.Initial;
struct TierConfig {
string stateName;
uint256 tierRatePercentage;
uint256 hardCap;
}
mapping(bytes32 => TierConfig) private tierConfigs;
// event for manual refund of cap overflow
event IncrementTieredState(string stateName);
/**
* checks the state when validating a purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
super._preValidatePurchase(_beneficiary, _weiAmount);
require(
state == SaleState.PrivateSale ||
state == SaleState.PreSale ||
state == SaleState.PublicSaleTier1 ||
state == SaleState.PublicSaleTier2 ||
state == SaleState.PublicSaleTier3 ||
state == SaleState.PublicSaleTier4
);
}
/**
* @dev Constructor
* Caveat emptor: this base contract is intended for inheritance by the Little Phil crowdsale only
*/
constructor() public {
// setup the map of bonus-rates for each SaleState tier
createSalesTierConfigMap();
}
/**
* @dev Overrides parent method taking into account variable rate (as a percentage).
* @param _weiAmount The value in wei to be converted into tokens
* @return The number of tokens _weiAmount wei will buy at present time.
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 currentTierRate = getCurrentTierRatePercentage();
uint256 requestedTokenAmount = _weiAmount.mul(rate).mul(currentTierRate).div(100);
uint256 remainingTokens = tokenCap.sub(tokensRaised);
// return number of LPC to provide
if(requestedTokenAmount > remainingTokens ) {
return remainingTokens;
}
return requestedTokenAmount;
}
/**
* @dev setup the map of bonus-rates (as a percentage) and total hardCap for each SaleState tier
* to be called by the constructor.
*/
function createSalesTierConfigMap() private {
tierConfigs [keccak256(SaleState.Initial)] = TierConfig({
stateName: "Initial",
tierRatePercentage:0,
hardCap: 0
});
tierConfigs [keccak256(SaleState.PrivateSale)] = TierConfig({
stateName: "PrivateSale",
tierRatePercentage:100,
hardCap: SafeMath.mul(400000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.FinalisedPrivateSale)] = TierConfig({
stateName: "FinalisedPrivateSale",
tierRatePercentage:0,
hardCap: 0
});
tierConfigs [keccak256(SaleState.PreSale)] = TierConfig({
stateName: "PreSale",
tierRatePercentage:140,
hardCap: SafeMath.mul(180000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.FinalisedPreSale)] = TierConfig({
stateName: "FinalisedPreSale",
tierRatePercentage:0,
hardCap: 0
});
tierConfigs [keccak256(SaleState.PublicSaleTier1)] = TierConfig({
stateName: "PublicSaleTier1",
tierRatePercentage:130,
hardCap: SafeMath.mul(265000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.PublicSaleTier2)] = TierConfig({
stateName: "PublicSaleTier2",
tierRatePercentage:120,
hardCap: SafeMath.mul(330000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.PublicSaleTier3)] = TierConfig({
stateName: "PublicSaleTier3",
tierRatePercentage:110,
hardCap: SafeMath.mul(375000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.PublicSaleTier4)] = TierConfig({
stateName: "PublicSaleTier4",
tierRatePercentage:100,
hardCap: SafeMath.mul(400000000, (10 ** 18))
});
tierConfigs [keccak256(SaleState.FinalisedPublicSale)] = TierConfig({
stateName: "FinalisedPublicSale",
tierRatePercentage:0,
hardCap: 0
});
tierConfigs [keccak256(SaleState.Closed)] = TierConfig({
stateName: "Closed",
tierRatePercentage:0,
hardCap: SafeMath.mul(400000000, (10 ** 18))
});
}
/**
* @dev get the current bonus-rate for the current SaleState
* @return the current rate as a percentage (e.g. 140 = 140% bonus)
*/
function getCurrentTierRatePercentage() public view returns (uint256) {
return tierConfigs[keccak256(state)].tierRatePercentage;
}
/**
* @dev get the current hardCap for the current SaleState
* @return the current hardCap
*/
function getCurrentTierHardcap() public view returns (uint256) {
return tierConfigs[keccak256(state)].hardCap;
}
/**
* @dev only allow the owner to modify the current SaleState
*/
function setState(uint256 _state) onlyOwner public {
state = SaleState(_state);
// update cap when state changes
tokenCap = getCurrentTierHardcap();
if(state == SaleState.Closed) {
crowdsaleClosed();
}
}
function getState() public view returns (string) {
return tierConfigs[keccak256(state)].stateName;
}
/**
* @dev only allow onwer to modify the current SaleState
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
super._updatePurchasingState(_beneficiary, _weiAmount);
if(capReached()) {
if(state == SaleState.PrivateSale) {
state = SaleState.FinalisedPrivateSale;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
else if(state == SaleState.PreSale) {
state = SaleState.FinalisedPreSale;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
else if(state == SaleState.PublicSaleTier1) {
state = SaleState.PublicSaleTier2;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
else if(state == SaleState.PublicSaleTier2) {
state = SaleState.PublicSaleTier3;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
else if(state == SaleState.PublicSaleTier3) {
state = SaleState.PublicSaleTier4;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
else if(state == SaleState.PublicSaleTier4) {
state = SaleState.FinalisedPublicSale;
tokenCap = getCurrentTierHardcap();
emit IncrementTieredState(getState());
}
}
}
/**
* Override for extensions that require an internal notification when the crowdsale has closed
*/
function crowdsaleClosed () internal {
// optional override
}
}
/* solium-disable security/no-block-members */
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
contract TokenVestingCrowdsale is Crowdsale, Ownable {
function addBeneficiaryVestor(
address beneficiaryWallet,
uint256 tokenAmount,
uint256 vestingEpocStart,
uint256 cliffInSeconds,
uint256 vestingEpocEnd
) external onlyOwner {
TokenVesting newVault = new TokenVesting(
beneficiaryWallet,
vestingEpocStart,
cliffInSeconds,
vestingEpocEnd,
false
);
LittlePhilCoin(token).mint(address(newVault), tokenAmount);
}
function releaseVestingTokens(address vaultAddress) external onlyOwner {
TokenVesting(vaultAddress).release(token);
}
}
contract LittlePhilCrowdsale is MintedCrowdsale, TieredCrowdsale, InitialSupplyCrowdsale, WhitelistedCrowdsale, TokenVestingCrowdsale {
/**
* Event for rate-change logging
* @param rate the new ETH-to_LPC exchange rate
*/
event NewRate(uint256 rate);
// Constructor
constructor(
uint256 _rate,
address _fundsWallet,
address[6] _wallets,
LittlePhilCoin _token
) public
Crowdsale(_rate, _fundsWallet, _token)
InitialSupplyCrowdsale(_wallets) {}
// Sets up the initial balances
// This must be called after ownership of the token is transferred to the crowdsale
function setupInitialState() external onlyOwner {
setupInitialSupply();
}
// Ownership management
function transferTokenOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0));
// I assume the crowdsale contract holds a reference to the token contract.
LittlePhilCoin(token).transferOwnership(_newOwner);
}
// Called at the end of the crowdsale when it is eneded
function crowdsaleClosed () internal {
uint256 remainingTokens = tokenCap.sub(tokensRaised);
_deliverTokens(airdropWallet, remainingTokens);
LittlePhilCoin(token).finishMinting();
}
/**
* checks the state when validating a purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= 500000000000000000);
}
/**
* @dev sets (updates) the ETH-to-LPC exchange rate
* @param _rate ate that will applied to ETH to derive how many LPC to mint
* does not affect, nor influenced by the bonus rates based on the current tier.
*/
function setRate(int _rate) public onlyOwner {
require(_rate > 0);
rate = uint256(_rate);
emit NewRate(rate);
}
/**
* @dev allows for minting from owner account
*/
function mintForPrivateFiat(address _beneficiary, uint256 _weiAmount) public onlyOwner {
require(_beneficiary != address(0));
// require(_weiAmount > 0);
_preValidatePurchase(_beneficiary, _weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(_weiAmount);
// update state
weiRaised = weiRaised.add(_weiAmount);
tokensRaised = tokensRaised.add(tokens);
if(capReached()) {
// manual process unused eth amount to sender
emit CapOverflow(_beneficiary, _weiAmount, tokens, now);
emit IncrementTieredState(getState());
}
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
_weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, _weiAmount);
_forwardFunds();
}
}
|
allows for minting from owner account/ require(_weiAmount > 0); calculate token amount to be created update state manual process unused eth amount to sender
|
function mintForPrivateFiat(address _beneficiary, uint256 _weiAmount) public onlyOwner {
require(_beneficiary != address(0));
_preValidatePurchase(_beneficiary, _weiAmount);
uint256 tokens = _getTokenAmount(_weiAmount);
weiRaised = weiRaised.add(_weiAmount);
tokensRaised = tokensRaised.add(tokens);
if(capReached()) {
emit CapOverflow(_beneficiary, _weiAmount, tokens, now);
emit IncrementTieredState(getState());
}
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
_weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, _weiAmount);
_forwardFunds();
}
| 6,264,767 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./ISchedule.sol";
contract Schedule is ISchedule {
address constant private precompile = address(0x0000000000000000000000000000000000000404);
/**
* @dev Schedule call the contract.
* Returns a bytes value equal to the task_id of the task created.
*/
function scheduleCall(
address contract_address,
uint256 value,
uint256 gas_limit,
uint256 storage_limit,
uint256 min_delay,
bytes memory input_data
) public override returns (bytes memory) {
require(contract_address != address(0), "ScheduleCall: the contract_address is the zero address");
require(input_data.length > 0, "ScheduleCall: input is null");
(bool success, bytes memory returnData) = precompile.call(abi.encodeWithSignature("scheduleCall(address,address,uint256,uint256,uint256,bytes)", msg.sender, contract_address, value, gas_limit, storage_limit, min_delay, input_data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
(bytes memory task_id) = abi.decode(returnData, (bytes));
emit ScheduledCall(msg.sender, contract_address, task_id);
return task_id;
}
/**
* @dev Cancel schedule call the contract.
* Returns a boolean value indicating whether the operation succeeded.
*/
function cancelCall(
bytes memory task_id
) public override returns (bool) {
(bool success, bytes memory returnData) = precompile.call(abi.encodeWithSignature("cancelCall(address,bytes)", msg.sender, task_id));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
emit CanceledCall(msg.sender, task_id);
return true;
}
/**
* @dev Reschedule call the contract.
* Returns a boolean value indicating whether the operation succeeded.
*/
function rescheduleCall(
uint256 min_delay,
bytes memory task_id
) public override returns (bool) {
(bool success, bytes memory returnData) = precompile.call(abi.encodeWithSignature("rescheduleCall(address,uint256,bytes)", msg.sender, min_delay, task_id));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
emit RescheduledCall(msg.sender, task_id);
return true;
}
}
|
Reschedule call the contract. Returns a boolean value indicating whether the operation succeeded./
|
function rescheduleCall(
uint256 min_delay,
bytes memory task_id
) public override returns (bool) {
(bool success, bytes memory returnData) = precompile.call(abi.encodeWithSignature("rescheduleCall(address,uint256,bytes)", msg.sender, min_delay, task_id));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
emit RescheduledCall(msg.sender, task_id);
return true;
}
| 13,035,244 |
pragma solidity 0.4.24;
import "./HMTokenInterface.sol";
import "./SafeMath.sol";
contract HMToken is HMTokenInterface {
using SafeMath for uint256;
uint256 private constant MAX_UINT256 = 2**256 - 1;
uint256 private constant BULK_MAX_VALUE = 1000000000 * (10 ** 18);
uint32 private constant BULK_MAX_COUNT = 100;
event BulkTransfer(uint256 indexed _txId, uint256 _bulkCount);
event BulkApproval(uint256 indexed _txId, uint256 _bulkCount);
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
string public name;
uint8 public decimals;
string public symbol;
constructor(uint256 _totalSupply, string _name, uint8 _decimals, string _symbol) public {
totalSupply = _totalSupply * (10 ** uint256(_decimals));
name = _name;
decimals = _decimals;
symbol = _symbol;
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
success = transferQuiet(_to, _value);
require(success, "Transfer didn't succeed");
return success;
}
function transferFrom(address _spender, address _to, uint256 _value) public returns (bool success) {
uint256 _allowance = allowed[_spender][msg.sender];
require(balances[_spender] >= _value && _allowance >= _value, "Spender balance or allowance too low");
require(_to != address(0), "Can't send tokens to uninitialized address");
balances[_spender] = balances[_spender].sub(_value);
balances[_to] = balances[_to].add(_value);
if (_allowance < MAX_UINT256) { // Special case to approve unlimited transfers
allowed[_spender][msg.sender] = allowed[_spender][msg.sender].sub(_value);
}
emit Transfer(_spender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_spender != address(0), "Token spender is an uninitialized address");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function increaseApproval(address _spender, uint _delta) public returns (bool success) {
require(_spender != address(0), "Token spender is an uninitialized address");
uint _oldValue = allowed[msg.sender][_spender];
if (_oldValue.add(_delta) < _oldValue || _oldValue.add(_delta) >= MAX_UINT256) { // Truncate upon overflow.
allowed[msg.sender][_spender] = MAX_UINT256.sub(1);
} else {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_delta);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _delta) public returns (bool success) {
require(_spender != address(0), "Token spender is an uninitialized address");
uint _oldValue = allowed[msg.sender][_spender];
if (_delta > _oldValue) { // Truncate upon overflow.
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].sub(_delta);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transferBulk(address[] _tos, uint256[] _values, uint256 _txId) public returns (uint256 _bulkCount) {
require(_tos.length == _values.length, "Amount of recipients and values don't match");
require(_tos.length < BULK_MAX_COUNT, "Too many recipients");
uint256 _bulkValue = 0;
for (uint j = 0; j < _tos.length; ++j) {
_bulkValue = _bulkValue.add(_values[j]);
}
require(_bulkValue < BULK_MAX_VALUE, "Bulk value too high");
_bulkCount = 0;
bool _success;
for (uint i = 0; i < _tos.length; ++i) {
_success = transferQuiet(_tos[i], _values[i]);
if (_success) {
_bulkCount = _bulkCount.add(1);
}
}
emit BulkTransfer(_txId, _bulkCount);
return _bulkCount;
}
function approveBulk(address[] _spenders, uint256[] _values, uint256 _txId) public returns (uint256 _bulkCount) {
require(_spenders.length == _values.length, "Amount of spenders and values don't match");
require(_spenders.length < BULK_MAX_COUNT, "Too many spenders");
uint256 _bulkValue = 0;
for (uint j = 0; j < _spenders.length; ++j) {
_bulkValue = _bulkValue.add(_values[j]);
}
require(_bulkValue < BULK_MAX_VALUE, "Bulk value too high");
_bulkCount = 0;
bool _success;
for (uint i = 0; i < _spenders.length; ++i) {
_success = increaseApproval(_spenders[i], _values[i]);
if (_success) {
_bulkCount = _bulkCount.add(1);
}
}
emit BulkApproval(_txId, _bulkCount);
return _bulkCount;
}
// Like transfer, but fails quietly.
function transferQuiet(address _to, uint256 _value) internal returns (bool success) {
if (_to == address(0)) return false; // Preclude burning tokens to uninitialized address.
if (_to == address(this)) return false; // Preclude sending tokens to the contract.
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
|
Like transfer, but fails quietly.
|
function transferQuiet(address _to, uint256 _value) internal returns (bool success) {
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 2,529,907 |
pragma solidity ^0.4.21;
// ----------------------------------------------------------------------------
// 'Digitize Coin - DTZ' token contract
//
// Symbol : DTZ
// Name : Digitize Coin
// Total supply: 200,000,000
// Decimals : 18
//
//
// (c) Radek Ostrowski / http://startonchain.com - The MIT Licence.
// ----------------------------------------------------------------------------
/**
* @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;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(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;
require(c >= a);
return c;
}
}
/**
* @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));
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
/**
* @title CutdownToken
* @dev Some ERC20 interface methods used in this contract
*/
contract CutdownToken {
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint256);
}
/**
* @title ApproveAndCallFallBack
* @dev Interface function called from `approveAndCall` notifying that the approval happened
*/
contract ApproveAndCallFallBack {
function receiveApproval(address _from, uint256 _amount, address _tokenContract, bytes _data) public returns (bool);
}
/**
* @title Digitize Coin
* @dev Burnable ERC20 token with initial transfers blocked
*/
contract DigitizeCoin is Ownable {
using SafeMath for uint256;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed _burner, uint256 _value);
event TransfersEnabled();
event TransferRightGiven(address indexed _to);
event TransferRightCancelled(address indexed _from);
event WithdrawnERC20Tokens(address indexed _tokenContract, address indexed _owner, uint256 _balance);
event WithdrawnEther(address indexed _owner, uint256 _balance);
event ApproveAndCall(address indexed _from, address indexed _to, uint256 _value, bytes _data);
string public constant name = "Digitize Coin";
string public constant symbol = "DTZ";
uint256 public constant decimals = 18;
uint256 public constant initialSupply = 200000000 * (10 ** decimals);
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) internal allowed;
//This mapping is used for the token owner and crowdsale contract to
//transfer tokens before they are transferable
mapping(address => bool) public transferGrants;
//This flag controls the global token transfer
bool public transferable;
/**
* @dev Modifier to check if tokens can be transfered.
*/
modifier canTransfer() {
require(transferable || transferGrants[msg.sender]);
_;
}
/**
* @dev The constructor sets the original `owner` of the contract
* to the sender account and assigns them all tokens.
*/
function DigitizeCoin() public {
owner = msg.sender;
totalSupply = initialSupply;
balances[owner] = totalSupply;
transferGrants[owner] = true;
}
/**
* @dev This contract does not accept any ether.
* Any forced ether can be withdrawn with `withdrawEther()` by the owner.
*/
function () payable public {
revert();
}
/**
* @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];
}
/**
* @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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer 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) canTransfer 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) canTransfer 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) canTransfer 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;
}
/**
* @dev Function to approve the transfer of the tokens and to call another contract in one step
* @param _recipient The target contract for tokens and function call
* @param _value The amount of tokens to send
* @param _data Extra data to be sent to the recipient contract function
*/
function approveAndCall(address _recipient, uint _value, bytes _data) public returns (bool) {
allowed[msg.sender][_recipient] = _value;
ApproveAndCallFallBack(_recipient).receiveApproval(msg.sender, _value, address(this), _data);
emit ApproveAndCall(msg.sender, _recipient, _value, _data);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
/**
* @dev Enables the transfer of tokens for everyone
*/
function enableTransfers() onlyOwner public {
require(!transferable);
transferable = true;
emit TransfersEnabled();
}
/**
* @dev Assigns the special transfer right, before transfers are enabled
* @param _to The address receiving the transfer grant
*/
function grantTransferRight(address _to) onlyOwner public {
require(!transferable);
require(!transferGrants[_to]);
require(_to != address(0));
transferGrants[_to] = true;
emit TransferRightGiven(_to);
}
/**
* @dev Removes the special transfer right, before transfers are enabled
* @param _from The address that the transfer grant is removed from
*/
function cancelTransferRight(address _from) onlyOwner public {
require(!transferable);
require(transferGrants[_from]);
transferGrants[_from] = false;
emit TransferRightCancelled(_from);
}
/**
* @dev Allows to transfer out the balance of arbitrary ERC20 tokens from the contract.
* @param _tokenContract The contract address of the ERC20 token.
*/
function withdrawERC20Tokens(address _tokenContract) onlyOwner public {
CutdownToken token = CutdownToken(_tokenContract);
uint256 totalBalance = token.balanceOf(address(this));
token.transfer(owner, totalBalance);
emit WithdrawnERC20Tokens(_tokenContract, owner, totalBalance);
}
/**
* @dev Allows to transfer out the ether balance that was forced into this contract, e.g with `selfdestruct`
*/
function withdrawEther() public onlyOwner {
uint256 totalBalance = address(this).balance;
require(totalBalance > 0);
owner.transfer(totalBalance);
emit WithdrawnEther(owner, totalBalance);
}
}
|
Assigns the special transfer right, before transfers are enabled _to The address receiving the transfer grant/
|
function grantTransferRight(address _to) onlyOwner public {
require(!transferable);
require(!transferGrants[_to]);
require(_to != address(0));
transferGrants[_to] = true;
emit TransferRightGiven(_to);
}
| 1,531,364 |
./partial_match/42/0xb739dd89190d5E71B41Eb224f7dA39e5dD4A8D12/sources/StabinolPriceOracle.sol
|
We will use a combination of the Twap and weighted averages to determine the current price Liquidity is gone/non-existant, can't update the price Uniswap twap price has updated, update our twap price Never had a price before, save the price accumulators Still no price calculation possible since no action on trading pair since last call First time price is calculated, set it to the twap price in USD Now calculate USD price from ETH Price There is already a price window and price, use weighted averages to determine the weight
|
function updateSTOLPrice() external {
lastSTOLPriceUpdate = now;
UniswapV2Pair pair = UniswapV2Pair(stolLiquidity);
(, uint112 reserve1, uint32 _blockTime) = pair.getReserves();
if(reserve1 == 0){
_stolUSDPrice = 0;
_stolPriceWindow = 0;
emit NoLiquidity();
return;
}
if(lastTWAPBlockTime != _blockTime){
if(lastTWAPCumulativePrice == 0){
if(_tokenIndex == 0){
lastTWAPCumulativePrice = pair.price0CumulativeLast();
lastTWAPCumulativePrice = pair.price1CumulativeLast();
}
lastTWAPBlockTime = _blockTime;
emit FirstPriceCapture();
return;
if(_tokenIndex == 0){
cumuPrice = pair.price0CumulativeLast();
cumuPrice = pair.price1CumulativeLast();
}
lastTWAPCumulativePrice = cumuPrice;
lastTWAPBlockTime = _blockTime;
}
}
if(lastTWAPPrice == 0){
emit FailedPriceCapture();
return;
}
if(_stolPriceWindow == 0){
_stolPriceWindow = updateFrequency;
_stolUSDPrice = getETHUSD() / 1e10 * lastTWAPPrice / 1e8;
uint256 price = getETHUSD() / 1e10 * lastTWAPPrice / 1e8;
_stolUSDPrice = (_stolUSDPrice * (_stolPriceWindow * DIVISION_FACTOR / (_stolPriceWindow + period)) / DIVISION_FACTOR);
_stolUSDPrice += (price * (period * DIVISION_FACTOR / (_stolPriceWindow + period)) / DIVISION_FACTOR);
}
}
| 3,478,769 |
./full_match/421613/0xA32f1cEd4332e31D81B5425268aF83823dc3BB13/sources/contracts/Material.sol
|
chest.burnBatch(opener, _chestIds, _amountsToOpen);chest.burn(opener, _chestId, _amountToOpen);emit ChestOpened(_chestId, opener, _amountToOpen, ids, values);
|
function openChest(
uint256[] memory _chestIds,
uint256[] memory _amountsToOpen
) external returns (uint256[] memory, uint256[] memory) {
address opener = msg.sender;
require(chest.balanceOf(opener, _chestIds[0]) >= _amountsToOpen[0], "!Bal");
(uint256[] memory tokenIds, uint256[] memory amounts) = getRewardUnits(_chestIds[0], _amountsToOpen[0]);
_mintBatch(opener, tokenIds, amounts, "");
return (tokenIds, amounts);
}
| 11,570,817 |
/**
*Submitted for verification at Etherscan.io on 2021-04-26
*/
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT AND Apache-2.0
// License: MIT
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Copied from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/solc-0.6/contracts/math/SafeMath.sol
*/
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) {
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;
}
}
// License: Apache-2.0
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param the RLP item.
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param the RLP item.
* @return (memPtr, len) pair: location of the item's payload in memory.
*/
function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) {
uint offset = _payloadOffset(item.memPtr);
uint memPtr = item.memPtr + offset;
uint len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @param the RLP item.
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
(, uint len) = payloadLocation(item);
return len;
}
/*
* @param the RLP item containing the encoded list.
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint memPtr, uint len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte except "0x80" is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
// SEE Github Issue #5.
// Summary: Most commonly used RLP libraries (i.e Geth) will encode
// "0" as "0x80" instead of as "0". We handle this edge case explicitly
// here.
if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
return true;
}
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
(uint memPtr, uint len) = payloadLocation(item);
uint result;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
(uint memPtr, uint len) = payloadLocation(item);
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(memPtr, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// License: MIT
/**
* Copied from https://github.com/lorenzb/proveth/blob/c74b20e/onchain/ProvethVerifier.sol
* with minor performance and code style-related modifications.
*/
library MerklePatriciaProofVerifier {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
/// @dev Validates a Merkle-Patricia-Trie proof.
/// If the proof proves the inclusion of some key-value pair in the
/// trie, the value is returned. Otherwise, i.e. if the proof proves
/// the exclusion of a key from the trie, an empty byte array is
/// returned.
/// @param rootHash is the Keccak-256 hash of the root node of the MPT.
/// @param path is the key of the node whose inclusion/exclusion we are
/// proving.
/// @param stack is the stack of MPT nodes (starting with the root) that
/// need to be traversed during verification.
/// @return value whose inclusion is proved or an empty byte array for
/// a proof of exclusion
function extractProofValue(
bytes32 rootHash,
bytes memory path,
RLPReader.RLPItem[] memory stack
) internal pure returns (bytes memory value) {
bytes memory mptKey = _decodeNibbles(path, 0);
uint256 mptKeyOffset = 0;
bytes32 nodeHashHash;
bytes memory rlpNode;
RLPReader.RLPItem[] memory node;
RLPReader.RLPItem memory rlpValue;
if (stack.length == 0) {
// Root hash of empty Merkle-Patricia-Trie
require(rootHash == 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421);
return new bytes(0);
}
// Traverse stack of nodes starting at root.
for (uint256 i = 0; i < stack.length; i++) {
// We use the fact that an rlp encoded list consists of some
// encoding of its length plus the concatenation of its
// *rlp-encoded* items.
// The root node is hashed with Keccak-256 ...
if (i == 0 && rootHash != stack[i].rlpBytesKeccak256()) {
revert();
}
// ... whereas all other nodes are hashed with the MPT
// hash function.
if (i != 0 && nodeHashHash != _mptHashHash(stack[i])) {
revert();
}
// We verified that stack[i] has the correct hash, so we
// may safely decode it.
node = stack[i].toList();
if (node.length == 2) {
// Extension or Leaf node
bool isLeaf;
bytes memory nodeKey;
(isLeaf, nodeKey) = _merklePatriciaCompactDecode(node[0].toBytes());
uint256 prefixLength = _sharedPrefixLength(mptKeyOffset, mptKey, nodeKey);
mptKeyOffset += prefixLength;
if (prefixLength < nodeKey.length) {
// Proof claims divergent extension or leaf. (Only
// relevant for proofs of exclusion.)
// An Extension/Leaf node is divergent iff it "skips" over
// the point at which a Branch node should have been had the
// excluded key been included in the trie.
// Example: Imagine a proof of exclusion for path [1, 4],
// where the current node is a Leaf node with
// path [1, 3, 3, 7]. For [1, 4] to be included, there
// should have been a Branch node at [1] with a child
// at 3 and a child at 4.
// Sanity check
if (i < stack.length - 1) {
// divergent node must come last in proof
revert();
}
return new bytes(0);
}
if (isLeaf) {
// Sanity check
if (i < stack.length - 1) {
// leaf node must come last in proof
revert();
}
if (mptKeyOffset < mptKey.length) {
return new bytes(0);
}
rlpValue = node[1];
return rlpValue.toBytes();
} else { // extension
// Sanity check
if (i == stack.length - 1) {
// shouldn't be at last level
revert();
}
if (!node[1].isList()) {
// rlp(child) was at least 32 bytes. node[1] contains
// Keccak256(rlp(child)).
nodeHashHash = node[1].payloadKeccak256();
} else {
// rlp(child) was less than 32 bytes. node[1] contains
// rlp(child).
nodeHashHash = node[1].rlpBytesKeccak256();
}
}
} else if (node.length == 17) {
// Branch node
if (mptKeyOffset != mptKey.length) {
// we haven't consumed the entire path, so we need to look at a child
uint8 nibble = uint8(mptKey[mptKeyOffset]);
mptKeyOffset += 1;
if (nibble >= 16) {
// each element of the path has to be a nibble
revert();
}
if (_isEmptyBytesequence(node[nibble])) {
// Sanity
if (i != stack.length - 1) {
// leaf node should be at last level
revert();
}
return new bytes(0);
} else if (!node[nibble].isList()) {
nodeHashHash = node[nibble].payloadKeccak256();
} else {
nodeHashHash = node[nibble].rlpBytesKeccak256();
}
} else {
// we have consumed the entire mptKey, so we need to look at what's contained in this node.
// Sanity
if (i != stack.length - 1) {
// should be at last level
revert();
}
return node[16].toBytes();
}
}
}
}
/// @dev Computes the hash of the Merkle-Patricia-Trie hash of the RLP item.
/// Merkle-Patricia-Tries use a weird "hash function" that outputs
/// *variable-length* hashes: If the item is shorter than 32 bytes,
/// the MPT hash is the item. Otherwise, the MPT hash is the
/// Keccak-256 hash of the item.
/// The easiest way to compare variable-length byte sequences is
/// to compare their Keccak-256 hashes.
/// @param item The RLP item to be hashed.
/// @return Keccak-256(MPT-hash(item))
function _mptHashHash(RLPReader.RLPItem memory item) private pure returns (bytes32) {
if (item.len < 32) {
return item.rlpBytesKeccak256();
} else {
return keccak256(abi.encodePacked(item.rlpBytesKeccak256()));
}
}
function _isEmptyBytesequence(RLPReader.RLPItem memory item) private pure returns (bool) {
if (item.len != 1) {
return false;
}
uint8 b;
uint256 memPtr = item.memPtr;
assembly {
b := byte(0, mload(memPtr))
}
return b == 0x80 /* empty byte string */;
}
function _merklePatriciaCompactDecode(bytes memory compact) private pure returns (bool isLeaf, bytes memory nibbles) {
require(compact.length > 0);
uint256 first_nibble = uint8(compact[0]) >> 4 & 0xF;
uint256 skipNibbles;
if (first_nibble == 0) {
skipNibbles = 2;
isLeaf = false;
} else if (first_nibble == 1) {
skipNibbles = 1;
isLeaf = false;
} else if (first_nibble == 2) {
skipNibbles = 2;
isLeaf = true;
} else if (first_nibble == 3) {
skipNibbles = 1;
isLeaf = true;
} else {
// Not supposed to happen!
revert();
}
return (isLeaf, _decodeNibbles(compact, skipNibbles));
}
function _decodeNibbles(bytes memory compact, uint256 skipNibbles) private pure returns (bytes memory nibbles) {
require(compact.length > 0);
uint256 length = compact.length * 2;
require(skipNibbles <= length);
length -= skipNibbles;
nibbles = new bytes(length);
uint256 nibblesLength = 0;
for (uint256 i = skipNibbles; i < skipNibbles + length; i += 1) {
if (i % 2 == 0) {
nibbles[nibblesLength] = bytes1((uint8(compact[i/2]) >> 4) & 0xF);
} else {
nibbles[nibblesLength] = bytes1((uint8(compact[i/2]) >> 0) & 0xF);
}
nibblesLength += 1;
}
assert(nibblesLength == nibbles.length);
}
function _sharedPrefixLength(uint256 xsOffset, bytes memory xs, bytes memory ys) private pure returns (uint256) {
uint256 i;
for (i = 0; i + xsOffset < xs.length && i < ys.length; i++) {
if (xs[i + xsOffset] != ys[i]) {
return i;
}
}
return i;
}
}
// License: MIT
/**
* @title A helper library for verification of Merkle Patricia account and state proofs.
*/
library Verifier {
using RLPReader for RLPReader.RLPItem;
using RLPReader for bytes;
uint256 constant HEADER_STATE_ROOT_INDEX = 3;
uint256 constant HEADER_NUMBER_INDEX = 8;
uint256 constant HEADER_TIMESTAMP_INDEX = 11;
struct BlockHeader {
bytes32 hash;
bytes32 stateRootHash;
uint256 number;
uint256 timestamp;
}
struct Account {
bool exists;
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct SlotValue {
bool exists;
uint256 value;
}
/**
* @notice Parses block header and verifies its presence onchain within the latest 256 blocks.
* @param _headerRlpBytes RLP-encoded block header.
*/
function verifyBlockHeader(bytes memory _headerRlpBytes)
internal view returns (BlockHeader memory)
{
BlockHeader memory header = parseBlockHeader(_headerRlpBytes);
// ensure that the block is actually in the blockchain
require(header.hash == blockhash(header.number), "blockhash mismatch");
return header;
}
/**
* @notice Parses RLP-encoded block header.
* @param _headerRlpBytes RLP-encoded block header.
*/
function parseBlockHeader(bytes memory _headerRlpBytes)
internal pure returns (BlockHeader memory)
{
BlockHeader memory result;
RLPReader.RLPItem[] memory headerFields = _headerRlpBytes.toRlpItem().toList();
result.stateRootHash = bytes32(headerFields[HEADER_STATE_ROOT_INDEX].toUint());
result.number = headerFields[HEADER_NUMBER_INDEX].toUint();
result.timestamp = headerFields[HEADER_TIMESTAMP_INDEX].toUint();
result.hash = keccak256(_headerRlpBytes);
return result;
}
/**
* @notice Verifies Merkle Patricia proof of an account and extracts the account fields.
*
* @param _addressHash Keccak256 hash of the address corresponding to the account.
* @param _stateRootHash MPT root hash of the Ethereum state trie.
*/
function extractAccountFromProof(
bytes32 _addressHash, // keccak256(abi.encodePacked(address))
bytes32 _stateRootHash,
RLPReader.RLPItem[] memory _proof
)
internal pure returns (Account memory)
{
bytes memory acctRlpBytes = MerklePatriciaProofVerifier.extractProofValue(
_stateRootHash,
abi.encodePacked(_addressHash),
_proof
);
Account memory account;
if (acctRlpBytes.length == 0) {
return account;
}
RLPReader.RLPItem[] memory acctFields = acctRlpBytes.toRlpItem().toList();
require(acctFields.length == 4);
account.exists = true;
account.nonce = acctFields[0].toUint();
account.balance = acctFields[1].toUint();
account.storageRoot = bytes32(acctFields[2].toUint());
account.codeHash = bytes32(acctFields[3].toUint());
return account;
}
/**
* @notice Verifies Merkle Patricia proof of a slot and extracts the slot's value.
*
* @param _slotHash Keccak256 hash of the slot position.
* @param _storageRootHash MPT root hash of the account's storage trie.
*/
function extractSlotValueFromProof(
bytes32 _slotHash,
bytes32 _storageRootHash,
RLPReader.RLPItem[] memory _proof
)
internal pure returns (SlotValue memory)
{
bytes memory valueRlpBytes = MerklePatriciaProofVerifier.extractProofValue(
_storageRootHash,
abi.encodePacked(_slotHash),
_proof
);
SlotValue memory value;
if (valueRlpBytes.length != 0) {
value.exists = true;
value.value = valueRlpBytes.toRlpItem().toUint();
}
return value;
}
}
// License: MIT
interface IPriceHelper {
function get_dy(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory xp,
uint256 A,
uint256 fee
) external pure returns (uint256);
}
interface IStableSwap {
function fee() external view returns (uint256);
function A_precise() external view returns (uint256);
}
/**
* @title
* A trustless oracle for the stETH/ETH Curve pool using Merkle Patricia
* proofs of Ethereum state.
*
* @notice
* The oracle currently assumes that the pool's fee and A (amplification
* coefficient) values don't change between the time of proof generation
* and submission.
*/
contract StableSwapStateOracle {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using SafeMath for uint256;
/**
* @notice Logs the updated slot values of Curve pool and stETH contracts.
*/
event SlotValuesUpdated(
uint256 timestamp,
uint256 poolEthBalance,
uint256 poolAdminEthBalance,
uint256 poolAdminStethBalance,
uint256 stethPoolShares,
uint256 stethTotalShares,
uint256 stethBeaconBalance,
uint256 stethBufferedEther,
uint256 stethDepositedValidators,
uint256 stethBeaconValidators
);
/**
* @notice Logs the updated stETH and ETH pool balances and the calculated stETH/ETH price.
*/
event PriceUpdated(
uint256 timestamp,
uint256 etherBalance,
uint256 stethBalance,
uint256 stethPrice
);
/**
* @notice Logs the updated price update threshold percentage advised to offchain clients.
*/
event PriceUpdateThresholdChanged(uint256 threshold);
/**
* @notice
* Logs the updated address having the right to change the advised price update threshold.
*/
event AdminChanged(address admin);
/// @dev Reporting data that is more fresh than this number of blocks ago is prohibited
uint256 constant public MIN_BLOCK_DELAY = 15;
// Constants for offchain proof generation
address constant public POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022;
address constant public STETH_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
/// @dev keccak256(abi.encodePacked(uint256(1)))
bytes32 constant public POOL_ADMIN_BALANCES_0_POS = 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6;
/// @dev bytes32(uint256(POOL_ADMIN_BALANCES_0_POS) + 1)
bytes32 constant public POOL_ADMIN_BALANCES_1_POS = 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf7;
/// @dev keccak256(uint256(0xdc24316b9ae028f1497c275eb9192a3ea0f67022) . uint256(0))
bytes32 constant public STETH_POOL_SHARES_POS = 0xae68078d7ee25b2b7bcb7d4b9fe9acf61f251fe08ff637df07889375d8385158;
/// @dev keccak256("lido.StETH.totalShares")
bytes32 constant public STETH_TOTAL_SHARES_POS = 0xe3b4b636e601189b5f4c6742edf2538ac12bb61ed03e6da26949d69838fa447e;
/// @dev keccak256("lido.Lido.beaconBalance")
bytes32 constant public STETH_BEACON_BALANCE_POS = 0xa66d35f054e68143c18f32c990ed5cb972bb68a68f500cd2dd3a16bbf3686483;
/// @dev keccak256("lido.Lido.bufferedEther")
bytes32 constant public STETH_BUFFERED_ETHER_POS = 0xed310af23f61f96daefbcd140b306c0bdbf8c178398299741687b90e794772b0;
/// @dev keccak256("lido.Lido.depositedValidators")
bytes32 constant public STETH_DEPOSITED_VALIDATORS_POS = 0xe6e35175eb53fc006520a2a9c3e9711a7c00de6ff2c32dd31df8c5a24cac1b5c;
/// @dev keccak256("lido.Lido.beaconValidators")
bytes32 constant public STETH_BEACON_VALIDATORS_POS = 0x9f70001d82b6ef54e9d3725b46581c3eb9ee3aa02b941b6aa54d678a9ca35b10;
// Constants for onchain proof verification
/// @dev keccak256(abi.encodePacked(POOL_ADDRESS))
bytes32 constant POOL_ADDRESS_HASH = 0xc70f76036d72b7bb865881e931082ea61bb4f13ec9faeb17f0591b18b6fafbd7;
/// @dev keccak256(abi.encodePacked(STETH_ADDRESS))
bytes32 constant STETH_ADDRESS_HASH = 0x6c958a912fe86c83262fbd4973f6bd042cef76551aaf679968f98665979c35e7;
/// @dev keccak256(abi.encodePacked(POOL_ADMIN_BALANCES_0_POS))
bytes32 constant POOL_ADMIN_BALANCES_0_HASH = 0xb5d9d894133a730aa651ef62d26b0ffa846233c74177a591a4a896adfda97d22;
/// @dev keccak256(abi.encodePacked(POOL_ADMIN_BALANCES_1_POS)
bytes32 constant POOL_ADMIN_BALANCES_1_HASH = 0xea7809e925a8989e20c901c4c1da82f0ba29b26797760d445a0ce4cf3c6fbd31;
/// @dev keccak256(abi.encodePacked(STETH_POOL_SHARES_POS)
bytes32 constant STETH_POOL_SHARES_HASH = 0xe841c8fb2710e169d6b63e1130fb8013d57558ced93619655add7aef8c60d4dc;
/// @dev keccak256(abi.encodePacked(STETH_TOTAL_SHARES_POS)
bytes32 constant STETH_TOTAL_SHARES_HASH = 0x4068b5716d4c00685289292c9cdc7e059e67159cd101476377efe51ba7ab8e9f;
/// @dev keccak256(abi.encodePacked(STETH_BEACON_BALANCE_POS)
bytes32 constant STETH_BEACON_BALANCE_HASH = 0xa6965d4729b36ed8b238f6ba55294196843f8be2850c5f63b6fb6d29181b50f8;
/// @dev keccak256(abi.encodePacked(STETH_BUFFERED_ETHER_POS)
bytes32 constant STETH_BUFFERED_ETHER_HASH = 0xa39079072910ef75f32ddc4f40104882abfc19580cc249c694e12b6de868ee1d;
/// @dev keccak256(abi.encodePacked(STETH_DEPOSITED_VALIDATORS_POS)
bytes32 constant STETH_DEPOSITED_VALIDATORS_HASH = 0x17216d3ffd8719eeee6d8052f7c1e6269bd92d2390d3e3fc4cde1f026e427fb3;
/// @dev keccak256(abi.encodePacked(STETH_BEACON_VALIDATORS_POS)
bytes32 constant STETH_BEACON_VALIDATORS_HASH = 0x6fd60d3960d8a32cbc1a708d6bf41bbce8152e61e72b2236d5e1ecede9c4cc72;
uint256 constant internal STETH_DEPOSIT_SIZE = 32 ether;
/**
* @dev A helper contract for calculating stETH/ETH price from its stETH and ETH balances.
*/
IPriceHelper internal helper;
/**
* @notice The admin has the right to set the suggested price update threshold (see below).
*/
address public admin;
/**
* @notice
* The price update threshold percentage advised to oracle clients.
* Expressed in basis points: 10000 BP equal to 100%, 100 BP to 1%.
*
* @dev
* If the current price in the pool differs less than this, the clients are advised to
* skip updating the oracle. However, this threshold is not enforced, so clients are
* free to update the oracle with any valid price.
*/
uint256 public priceUpdateThreshold;
/**
* @notice The timestamp of the proven pool state/price.
*/
uint256 public timestamp;
/**
* @notice The proven ETH balance of the pool.
*/
uint256 public etherBalance;
/**
* @notice The proven stETH balance of the pool.
*/
uint256 public stethBalance;
/**
* @notice The proven stETH/ETH price in the pool.
*/
uint256 public stethPrice;
/**
* @param _helper Address of the deployed instance of the StableSwapPriceHelper.vy contract.
* @param _admin The address that has the right to set the suggested price update threshold.
* @param _priceUpdateThreshold The initial value of the suggested price update threshold.
* Expressed in basis points, 10000 BP corresponding to 100%.
*/
constructor(IPriceHelper _helper, address _admin, uint256 _priceUpdateThreshold) public {
helper = _helper;
_setAdmin(_admin);
_setPriceUpdateThreshold(_priceUpdateThreshold);
}
/**
* @notice Passes the right to set the suggested price update threshold to a new address.
*/
function setAdmin(address _admin) external {
require(msg.sender == admin);
_setAdmin(_admin);
}
/**
* @notice Sets the suggested price update threshold.
*
* @param _priceUpdateThreshold The suggested price update threshold.
* Expressed in basis points, 10000 BP corresponding to 100%.
*/
function setPriceUpdateThreshold(uint256 _priceUpdateThreshold) external {
require(msg.sender == admin);
_setPriceUpdateThreshold(_priceUpdateThreshold);
}
/**
* @notice Retuens a set of values used by the clients for proof generation.
*/
function getProofParams() external view returns (
address poolAddress,
address stethAddress,
bytes32 poolAdminEtherBalancePos,
bytes32 poolAdminCoinBalancePos,
bytes32 stethPoolSharesPos,
bytes32 stethTotalSharesPos,
bytes32 stethBeaconBalancePos,
bytes32 stethBufferedEtherPos,
bytes32 stethDepositedValidatorsPos,
bytes32 stethBeaconValidatorsPos,
uint256 advisedPriceUpdateThreshold
) {
return (
POOL_ADDRESS,
STETH_ADDRESS,
POOL_ADMIN_BALANCES_0_POS,
POOL_ADMIN_BALANCES_1_POS,
STETH_POOL_SHARES_POS,
STETH_TOTAL_SHARES_POS,
STETH_BEACON_BALANCE_POS,
STETH_BUFFERED_ETHER_POS,
STETH_DEPOSITED_VALIDATORS_POS,
STETH_BEACON_VALIDATORS_POS,
priceUpdateThreshold
);
}
/**
* @return _timestamp The timestamp of the proven pool state/price.
* @return _etherBalance The proven ETH balance of the pool.
* @return _stethBalance The proven stETH balance of the pool.
* @return _stethPrice The proven stETH/ETH price in the pool.
*/
function getState() external view returns (
uint256 _timestamp,
uint256 _etherBalance,
uint256 _stethBalance,
uint256 _stethPrice
) {
return (timestamp, etherBalance, stethBalance, stethPrice);
}
/**
* @notice Used by the offchain clients to submit the proof.
*
* @dev Reverts unless:
* - the block the submitted data corresponds to is in the chain;
* - the block is at least `MIN_BLOCK_DELAY` blocks old;
* - all submitted proofs are valid.
*
* @param _blockHeaderRlpBytes RLP-encoded block header.
*
* @param _proofRlpBytes RLP-encoded list of Merkle Patricia proofs:
* 1. proof of the Curve pool contract account;
* 2. proof of the stETH contract account;
* 3. proof of the `admin_balances[0]` slot of the Curve pool contract;
* 4. proof of the `admin_balances[1]` slot of the Curve pool contract;
* 5. proof of the `shares[0xDC24316b9AE028F1497c275EB9192a3Ea0f67022]` slot of stETH contract;
* 6. proof of the `keccak256("lido.StETH.totalShares")` slot of stETH contract;
* 7. proof of the `keccak256("lido.Lido.beaconBalance")` slot of stETH contract;
* 8. proof of the `keccak256("lido.Lido.bufferedEther")` slot of stETH contract;
* 9. proof of the `keccak256("lido.Lido.depositedValidators")` slot of stETH contract;
* 10. proof of the `keccak256("lido.Lido.beaconValidators")` slot of stETH contract.
*/
function submitState(bytes memory _blockHeaderRlpBytes, bytes memory _proofRlpBytes)
external
{
Verifier.BlockHeader memory blockHeader = Verifier.verifyBlockHeader(_blockHeaderRlpBytes);
{
uint256 currentBlock = block.number;
// ensure block finality
require(
currentBlock > blockHeader.number &&
currentBlock - blockHeader.number >= MIN_BLOCK_DELAY,
"block too fresh"
);
}
require(blockHeader.timestamp > timestamp, "stale data");
RLPReader.RLPItem[] memory proofs = _proofRlpBytes.toRlpItem().toList();
require(proofs.length == 10, "total proofs");
Verifier.Account memory accountPool = Verifier.extractAccountFromProof(
POOL_ADDRESS_HASH,
blockHeader.stateRootHash,
proofs[0].toList()
);
require(accountPool.exists, "accountPool");
Verifier.Account memory accountSteth = Verifier.extractAccountFromProof(
STETH_ADDRESS_HASH,
blockHeader.stateRootHash,
proofs[1].toList()
);
require(accountSteth.exists, "accountSteth");
Verifier.SlotValue memory slotPoolAdminBalances0 = Verifier.extractSlotValueFromProof(
POOL_ADMIN_BALANCES_0_HASH,
accountPool.storageRoot,
proofs[2].toList()
);
require(slotPoolAdminBalances0.exists, "adminBalances0");
Verifier.SlotValue memory slotPoolAdminBalances1 = Verifier.extractSlotValueFromProof(
POOL_ADMIN_BALANCES_1_HASH,
accountPool.storageRoot,
proofs[3].toList()
);
require(slotPoolAdminBalances1.exists, "adminBalances1");
Verifier.SlotValue memory slotStethPoolShares = Verifier.extractSlotValueFromProof(
STETH_POOL_SHARES_HASH,
accountSteth.storageRoot,
proofs[4].toList()
);
require(slotStethPoolShares.exists, "poolShares");
Verifier.SlotValue memory slotStethTotalShares = Verifier.extractSlotValueFromProof(
STETH_TOTAL_SHARES_HASH,
accountSteth.storageRoot,
proofs[5].toList()
);
require(slotStethTotalShares.exists, "totalShares");
Verifier.SlotValue memory slotStethBeaconBalance = Verifier.extractSlotValueFromProof(
STETH_BEACON_BALANCE_HASH,
accountSteth.storageRoot,
proofs[6].toList()
);
require(slotStethBeaconBalance.exists, "beaconBalance");
Verifier.SlotValue memory slotStethBufferedEther = Verifier.extractSlotValueFromProof(
STETH_BUFFERED_ETHER_HASH,
accountSteth.storageRoot,
proofs[7].toList()
);
require(slotStethBufferedEther.exists, "bufferedEther");
Verifier.SlotValue memory slotStethDepositedValidators = Verifier.extractSlotValueFromProof(
STETH_DEPOSITED_VALIDATORS_HASH,
accountSteth.storageRoot,
proofs[8].toList()
);
require(slotStethDepositedValidators.exists, "depositedValidators");
Verifier.SlotValue memory slotStethBeaconValidators = Verifier.extractSlotValueFromProof(
STETH_BEACON_VALIDATORS_HASH,
accountSteth.storageRoot,
proofs[9].toList()
);
require(slotStethBeaconValidators.exists, "beaconValidators");
emit SlotValuesUpdated(
blockHeader.timestamp,
accountPool.balance,
slotPoolAdminBalances0.value,
slotPoolAdminBalances1.value,
slotStethPoolShares.value,
slotStethTotalShares.value,
slotStethBeaconBalance.value,
slotStethBufferedEther.value,
slotStethDepositedValidators.value,
slotStethBeaconValidators.value
);
uint256 newEtherBalance = accountPool.balance.sub(slotPoolAdminBalances0.value);
uint256 newStethBalance = _getStethBalanceByShares(
slotStethPoolShares.value,
slotStethTotalShares.value,
slotStethBeaconBalance.value,
slotStethBufferedEther.value,
slotStethDepositedValidators.value,
slotStethBeaconValidators.value
).sub(slotPoolAdminBalances1.value);
uint256 newStethPrice = _calcPrice(newEtherBalance, newStethBalance);
timestamp = blockHeader.timestamp;
etherBalance = newEtherBalance;
stethBalance = newStethBalance;
stethPrice = newStethPrice;
emit PriceUpdated(blockHeader.timestamp, newEtherBalance, newStethBalance, newStethPrice);
}
/**
* @dev Given the values of stETH smart contract slots, calculates the amount of stETH owned
* by the Curve pool by reproducing calculations performed in the stETH contract.
*/
function _getStethBalanceByShares(
uint256 _shares,
uint256 _totalShares,
uint256 _beaconBalance,
uint256 _bufferedEther,
uint256 _depositedValidators,
uint256 _beaconValidators
)
internal pure returns (uint256)
{
// https://github.com/lidofinance/lido-dao/blob/v1.0.0/contracts/0.4.24/StETH.sol#L283
// https://github.com/lidofinance/lido-dao/blob/v1.0.0/contracts/0.4.24/Lido.sol#L719
// https://github.com/lidofinance/lido-dao/blob/v1.0.0/contracts/0.4.24/Lido.sol#L706
if (_totalShares == 0) {
return 0;
}
uint256 transientBalance = _depositedValidators.sub(_beaconValidators).mul(STETH_DEPOSIT_SIZE);
uint256 totalPooledEther = _bufferedEther.add(_beaconBalance).add(transientBalance);
return _shares.mul(totalPooledEther).div(_totalShares);
}
/**
* @dev Given the ETH and stETH balances of the Curve pool, calculates the corresponding
* stETH/ETH price by reproducing calculations performed in the pool contract.
*/
function _calcPrice(uint256 _etherBalance, uint256 _stethBalance) internal view returns (uint256) {
uint256 A = IStableSwap(POOL_ADDRESS).A_precise();
uint256 fee = IStableSwap(POOL_ADDRESS).fee();
return helper.get_dy(1, 0, 10**18, [_etherBalance, _stethBalance], A, fee);
}
function _setPriceUpdateThreshold(uint256 _priceUpdateThreshold) internal {
require(_priceUpdateThreshold <= 10000);
priceUpdateThreshold = _priceUpdateThreshold;
emit PriceUpdateThresholdChanged(_priceUpdateThreshold);
}
function _setAdmin(address _admin) internal {
require(_admin != address(0));
require(_admin != admin);
admin = _admin;
emit AdminChanged(_admin);
}
}
|
Computes the hash of the Merkle-Patricia-Trie hash of the RLP item. Merkle-Patricia-Tries use a weird "hash function" that outputs variable-length hashes: If the item is shorter than 32 bytes, the MPT hash is the item. Otherwise, the MPT hash is the Keccak-256 hash of the item. The easiest way to compare variable-length byte sequences is to compare their Keccak-256 hashes. item The RLP item to be hashed. return Keccak-256(MPT-hash(item))
|
function _mptHashHash(RLPReader.RLPItem memory item) private pure returns (bytes32) {
if (item.len < 32) {
return item.rlpBytesKeccak256();
return keccak256(abi.encodePacked(item.rlpBytesKeccak256()));
}
}
| 10,563,899 |
./full_match/137/0x6857D601E199e7dC2Da276bc6E860124948B4F34/sources/project_/contracts/Pool.sol
|
/ calculates the gross interest handling impermanent loss case this condition is added because emit is to only be emitted when adminFeeSet flag is false but this mehtod is called for every player withdrawal in variable deposit pool.
|
function _calculateAndUpdateGameAccounting(uint256 _totalBalance, uint256[] memory _grossRewardTokenAmount)
internal
returns (uint256)
{
uint256 _grossInterest = 0;
if (_totalBalance >= netTotalGamePrincipal) {
_grossInterest = _totalBalance - netTotalGamePrincipal;
impermanentLossShare = (_totalBalance * 100) / netTotalGamePrincipal;
netTotalGamePrincipal = _totalBalance;
}
if (_incentiveToken != address(0)) {
try IERC20(_incentiveToken).balanceOf(address(this)) returns (uint256 _totalIncentiveAmount) {
totalIncentiveAmount = _totalIncentiveAmount;
emit ExternalTokenGetBalanceError(_incentiveToken, reason);
}
}
if (!adminFeeSet) {
emit EndGameStats(
msg.sender,
_totalBalance,
totalGamePrincipal,
netTotalGamePrincipal,
_grossInterest,
_grossRewardTokenAmount,
totalIncentiveAmount,
impermanentLossShare
);
}
return _grossInterest;
}
Calculates and set's admin accounting called by methods _setGlobalPoolParams.
Updates the admin fee storage var used for admin fee.
@param _grossInterest Gross interest amount.
@param _grossRewardTokenAmount Gross reward amount array.
| 4,741,889 |
// Dependency 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);
}
// Dependency 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;
}
}
// Root file: contracts/cVToken.sol
pragma solidity 0.6.12;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
contract cVToken is IERC20 {
using SafeMath for uint256;
uint256 constant private MAX_UINT256 = ~uint256(0);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name = "cVToken";
string private _symbol = "cV";
uint8 private _decimals = 18;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
constructor () public {
_totalSupply = 9931143978000000000000000000; // https://etherscan.io/address/0xda6cb58a0d0c01610a29c5a65c303e13e885887c
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(_name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
/**
* @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(msg.sender, 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(msg.sender, 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);
if (_allowances[sender][msg.sender] < MAX_UINT256) { // treat MAX_UINT256 approve as infinite approval
_approve(sender, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][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(msg.sender, spender, _allowances[msg.sender][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");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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");
_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 Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function transferMany(address[] calldata recipients, uint256[] calldata amounts) external {
require(recipients.length == amounts.length, "cVToken: Wrong array length");
uint256 total = 0;
for (uint256 i = 0; i < amounts.length; i++) {
total = total.add(amounts[i]);
}
_balances[msg.sender] = _balances[msg.sender].sub(total, "ERC20: transfer amount exceeds balance");
for (uint256 i = 0; i < recipients.length; i++) {
address recipient = recipients[i];
uint256 amount = amounts[i];
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(msg.sender, recipient, amount);
}
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'cVToken: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'cVToken: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
|
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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
| 10,971,844 |
./partial_match/1/0x30ACF449995Dc0d1cB6d83983f589bB774912D4A/sources/SHIBFROG.sol
|
Moves `amount` of tokens from `from` to `to`. This 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "IERC20Simp: transfer from the zero address");
require(to != address(0), "IERC20Simp: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "IERC20Simp: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
| 9,341,124 |
//Address: 0x0b6f6e073a08ab8fd458527c47ed83982ff26851
//Contract name: VoteFactory
//Balance: 0 Ether
//Verification Date: 6/1/2017
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.10;
contract VoteFactory {
address public owner;
uint public numPolls;
uint public nextEndTime;
Vote public yesContract;
Vote public noContract;
mapping(uint => string) public voteDescription;
mapping(address => mapping(uint => bool)) public hasVoted;
mapping(uint => uint) public numVoters; // number of voters per round
mapping(uint => mapping(uint => address)) public voter; // [voteId][voterNumber] => address
mapping(uint => uint) public yesCount; // number of yes for a given round
mapping(uint => uint) public noCount;
event transferredOwner(address newOwner);
event startedNewVote(address initiator, uint duration, string description, uint voteId);
event voted(address voter, bool isYes);
modifier onlyOwner {
if (msg.sender != owner)
throw;
_;
}
function transferOwner(address newOwner) onlyOwner {
owner = newOwner;
transferredOwner(newOwner);
}
function payOut() onlyOwner {
// just in case we accumulate a balance here, we have to be able to retrieve it
owner.send(this.balance);
}
function VoteFactory() {
owner = msg.sender;
// constructor deploys yes and no contract
yesContract = new Vote();
noContract = new Vote();
}
function() payable {
// default function starts new poll if previous poll is over for at least 10 minutes
if (nextEndTime < now + 10 minutes)
startNewVote(10 minutes, "Vote on tax reimbursements");
}
function newVote(uint duration, string description) onlyOwner {
// only admin is able to start vote with arbitrary duration
startNewVote(duration, description);
}
function startNewVote(uint duration, string description) internal {
// do not allow to start new vote if there's still something ongoing
if (now <= nextEndTime)
throw;
nextEndTime = now + duration;
voteDescription[numPolls] = description;
startedNewVote(msg.sender, duration, description, ++numPolls);
}
function vote(bool isYes, address voteSender) {
// voting should just be able via voting contract (use them as SWIS contracts)
if (msg.sender != address(yesContract) && msg.sender != address(noContract))
throw;
// throw if time is over
if (now > nextEndTime)
throw;
// throw if sender has already voted before
if (hasVoted[voteSender][numPolls])
throw;
hasVoted[voteSender][numPolls] = true;
voter[numPolls][numVoters[numPolls]++] = voteSender;
if (isYes)
yesCount[numPolls]++;
else
noCount[numPolls]++;
voted(voteSender, isYes);
}
}
contract Vote {
VoteFactory public myVoteFactory;
function Vote() {
// constructor expects to be called by VoteFactory contract
myVoteFactory = VoteFactory(msg.sender);
}
function () payable {
// make payable so that wallets that cannot send tx with 0 Wei still work
myVoteFactory.vote(this == myVoteFactory.yesContract(), msg.sender);
}
function payOut() {
// just to collect accidentally accumulated funds
msg.sender.send(this.balance);
}
}
|
voting should just be able via voting contract (use them as SWIS contracts) throw if time is over throw if sender has already voted before
|
function vote(bool isYes, address voteSender) {
if (msg.sender != address(yesContract) && msg.sender != address(noContract))
throw;
if (now > nextEndTime)
throw;
if (hasVoted[voteSender][numPolls])
throw;
hasVoted[voteSender][numPolls] = true;
voter[numPolls][numVoters[numPolls]++] = voteSender;
if (isYes)
yesCount[numPolls]++;
else
noCount[numPolls]++;
voted(voteSender, isYes);
}
| 13,139,238 |
pragma solidity ^0.4.25;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
// File: 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: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query 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];
}
/**
* @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 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_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 decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @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, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: 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));
require(!has(role, account));
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));
require(has(role, account));
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: 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() internal {
_addMinter(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 {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor(uint256 cap)
public
{
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns(uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: 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: openzeppelin-solidity/contracts/introspection/ERC165Checker.sol
/**
* @title ERC165Checker
* @dev Use `using ERC165Checker for address`; to include this library
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _InterfaceId_Invalid = 0xffffffff;
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @notice Query if a contract supports ERC165
* @param account The address of the contract to query for support of ERC165
* @return true if the contract at account implements ERC165
*/
function _supportsERC165(address account)
internal
view
returns (bool)
{
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _InterfaceId_ERC165) &&
!_supportsERC165Interface(account, _InterfaceId_Invalid);
}
/**
* @notice Query if a contract implements an interface, also checks support of ERC165
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Interface identification is specified in ERC-165.
*/
function _supportsInterface(address account, bytes4 interfaceId)
internal
view
returns (bool)
{
// query support of both ERC165 as per the spec and support of _interfaceId
return _supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @notice Query if a contract implements interfaces, also checks support of ERC165
* @param account The address of the contract to query for support of an interface
* @param interfaceIds A list of interface identifiers, as specified in ERC-165
* @return true if the contract at account indicates support all interfaces in the
* interfaceIds list, false otherwise
* @dev Interface identification is specified in ERC-165.
*/
function _supportsAllInterfaces(address account, bytes4[] interfaceIds)
internal
view
returns (bool)
{
// query support of ERC165 itself
if (!_supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with the `supportsERC165` method in this library.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId)
private
view
returns (bool)
{
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(
account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(
address account,
bytes4 interfaceId
)
private
view
returns (bool success, bool result)
{
bytes memory encodedParams = abi.encodeWithSelector(
_InterfaceId_ERC165,
interfaceId
);
// solium-disable-next-line security/no-inline-assembly
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
account, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
}
}
// File: 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: 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) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_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;
}
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol
/**
* @title IERC1363 Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for a Payable Token contract as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363 is IERC20, ERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address
* and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) public returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address
* and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes data) public returns (bool); // solium-disable-line max-len
/**
* @notice Transfer tokens from one address to another
* and then call `onTransferReceived` on receiver
* @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
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) public returns (bool); // solium-disable-line max-len
/**
* @notice Transfer tokens from one address to another
* and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes data) public returns (bool); // solium-disable-line max-len, arg-overflow
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) public returns (bool); // solium-disable-line max-len
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes data) public returns (bool); // solium-disable-line max-len
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol
/**
* @title IERC1363Receiver Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes data) external returns (bytes4); // solium-disable-line max-len, arg-overflow
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol
/**
* @title IERC1363Spender Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support approveAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes data) external returns (bytes4); // solium-disable-line max-len
}
// File: erc-payable-token/contracts/token/ERC1363/ERC1363.sol
/**
* @title ERC1363
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation of an ERC1363 interface
*/
contract ERC1363 is ERC20, IERC1363 { // solium-disable-line max-len
using Address for address;
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
bytes4 internal constant _InterfaceId_ERC1363Transfer = 0x4bbee2df;
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
bytes4 internal constant _InterfaceId_ERC1363Approve = 0xfb9ec8ce;
// Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector`
bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c;
// Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
// which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector`
bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0;
constructor() public {
// register the supported interfaces to conform to ERC1363 via ERC165
_registerInterface(_InterfaceId_ERC1363Transfer);
_registerInterface(_InterfaceId_ERC1363Approve);
}
function transferAndCall(
address to,
uint256 value
)
public
returns (bool)
{
return transferAndCall(to, value, "");
}
function transferAndCall(
address to,
uint256 value,
bytes data
)
public
returns (bool)
{
require(transfer(to, value));
require(
_checkAndCallTransfer(
msg.sender,
to,
value,
data
)
);
return true;
}
function transferFromAndCall(
address from,
address to,
uint256 value
)
public
returns (bool)
{
// solium-disable-next-line arg-overflow
return transferFromAndCall(from, to, value, "");
}
function transferFromAndCall(
address from,
address to,
uint256 value,
bytes data
)
public
returns (bool)
{
require(transferFrom(from, to, value));
require(
_checkAndCallTransfer(
from,
to,
value,
data
)
);
return true;
}
function approveAndCall(
address spender,
uint256 value
)
public
returns (bool)
{
return approveAndCall(spender, value, "");
}
function approveAndCall(
address spender,
uint256 value,
bytes data
)
public
returns (bool)
{
approve(spender, value);
require(
_checkAndCallApprove(
spender,
value,
data
)
);
return true;
}
/**
* @dev Internal function to invoke `onTransferReceived` 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 value
* @param to address Target address that will receive the tokens
* @param value uint256 The amount mount of tokens 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 _checkAndCallTransfer(
address from,
address to,
uint256 value,
bytes data
)
internal
returns (bool)
{
if (!to.isContract()) {
return false;
}
bytes4 retval = IERC1363Receiver(to).onTransferReceived(
msg.sender, from, value, data
);
return (retval == _ERC1363_RECEIVED);
}
/**
* @dev Internal function to invoke `onApprovalReceived` on a target address
* The call is not executed if the target address is not a contract
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkAndCallApprove(
address spender,
uint256 value,
bytes data
)
internal
returns (bool)
{
if (!spender.isContract()) {
return false;
}
bytes4 retval = IERC1363Spender(spender).onApprovalReceived(
msg.sender, value, data
);
return (retval == _ERC1363_APPROVED);
}
}
// File: 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 OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 OwnershipTransferred(_owner, address(0));
_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: eth-token-recover/contracts/TokenRecover.sol
/**
* @title TokenRecover
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Allow to recover any ERC20 sent into the contract for error
*/
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(
address tokenAddress,
uint256 tokenAmount
)
public
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// File: contracts/access/roles/OperatorRole.sol
contract OperatorRole {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
Roles.Role private _operators;
constructor() internal {
_addOperator(msg.sender);
}
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function addOperator(address account) public onlyOperator {
_addOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
}
// File: contracts/token/BaseToken.sol
/**
* @title BaseToken
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation of the BaseToken
*/
contract BaseToken is ERC20Detailed, ERC20Capped, ERC20Burnable, ERC1363, OperatorRole, TokenRecover {
event MintFinished();
// indicates if minting is finished
bool public _mintingFinished = false;
/**
* @dev Tokens can be minted only before minting finished
*/
modifier canMint() {
require(!_mintingFinished);
_;
}
/**
* @dev Tokens can be moved only after minting finished or if you are an approved operator
*/
modifier canTransfer(address from) {
require(_mintingFinished || isOperator(from));
_;
}
/**
* @param name Name of the token
* @param symbol A symbol to be used as ticker
* @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit
* @param cap Maximum number of tokens mintable
*/
constructor(
string name,
string symbol,
uint8 decimals,
uint256 cap
)
ERC20Detailed(name, symbol, decimals)
ERC20Capped(cap)
public
{}
/**
* @return if minting is finished or not
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
function mint(address to, uint256 value) public canMint returns (bool) {
return super.mint(to, value);
}
function transfer(address to, uint256 value) public canTransfer(msg.sender) returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public canTransfer(from) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Function to stop minting new tokens.
*/
function finishMinting() public onlyOwner canMint {
_mintingFinished = true;
emit MintFinished();
}
/**
* @dev remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
/**
* @dev remove the `minter` role from address
* @param account Address you want to remove role
*/
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
}
// File: contracts/token/ShakaToken.sol
/**
* @title ShakaToken
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation of the Shaka Token
*/
contract ShakaToken is BaseToken {
/**
* @param name Name of the token
* @param symbol A symbol to be used as ticker
* @param decimals Number of decimals. All the operations are done using the smallest and indivisible token unit
* @param cap Maximum number of tokens mintable
*/
constructor(
string name,
string symbol,
uint8 decimals,
uint256 cap
)
BaseToken(name, symbol, decimals, cap)
public
{}
}
|
Query if a contract implements interfaces, also checks support of ERC165 account The address of the contract to query for support of an interface interfaceIds A list of interface identifiers, as specified in ERC-165 return true if the contract at account indicates support all interfaces in the interfaceIds list, false otherwise Interface identification is specified in ERC-165./ query support of ERC165 itself query support of each interface in _interfaceIds
|
function _supportsAllInterfaces(address account, bytes4[] interfaceIds)
internal
view
returns (bool)
{
if (!_supportsERC165(account)) {
return false;
}
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
}
| 7,794,291 |
pragma solidity ^0.4.16;
// METADOLLAR (DOL) VAULT - COPYRIGHT 2018 METADOLLAR.ORG
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal pure {
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Reverts if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy 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))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_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;
}
function indexOf(string _haystack, string _needle) internal pure 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))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
contract ERC20Interface {
/// @notice Total supply of Metadollar
function totalSupply() constant returns (uint256 totalAmount);
/// @notice Get the account balance of another account with address_owner
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Send_value amount of tokens to address_to
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Send_value amount of tokens from address_from to address_to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice Allow_spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success);
/// @notice Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
/// @notice Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @notice Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract owned{
address public owner;
address constant supervisor = 0x772F3122a8687ee3401bafCA91e873CC37106a7A;//0x97f7298435e5a8180747E89DBa7759674c5c35a5;
function owned(){
owner = msg.sender;
}
/// @notice Functions with this modifier can only be executed by the owner
modifier isOwner {
assert(msg.sender == owner || msg.sender == supervisor);
_;
}
/// @notice Transfer the ownership of this contract
function transferOwnership(address newOwner);
event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner);
}
contract METADOLLAR is ERC20Interface, owned, SafeMath, usingOraclize {
string public constant name = "METADOLLAR";
string public constant symbol = "DOL";
uint public constant decimals = 18;
uint256 public _totalSupply = 1000000000000000000000000000;
uint256 public icoMin = 1000000000000000000000000000;
uint256 public preIcoLimit = 1;
uint256 public countHolders = 0; // Number of DOL holders
uint256 public amountOfInvestments = 0; // amount of collected wei
uint256 bank;
uint256 preICOprice;
uint256 ICOprice;
uint256 public currentTokenPrice; // Current Price of DOL
uint256 public commRate;
bool public preIcoIsRunning;
bool public minimalGoalReached;
bool public icoIsClosed;
bool icoExitIsPossible;
//Balances for each account
mapping (address => uint256) public tokenBalanceOf;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
//list with information about frozen accounts
mapping(address => bool) frozenAccount;
//this generate a public event on a blockchain that will notify clients
event FrozenFunds(address initiator, address account, string status);
//this generate a public event on a blockchain that will notify clients
event BonusChanged(uint8 bonusOld, uint8 bonusNew);
//this generate a public event on a blockchain that will notify clients
event minGoalReached(uint256 minIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event preIcoEnded(uint256 preIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice);
//this generate a public event on a blockchain that will notify clients
event withdrawed(address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event deposited(address _from, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenCreated(address _creator, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenDestroyed(address _destroyer, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event icoStatusUpdated(address _initiator, string status);
/// @notice Constructor of the contract
function METADOLLAR() {
preIcoIsRunning = false;
minimalGoalReached = true;
icoExitIsPossible = false;
icoIsClosed = false;
tokenBalanceOf[this] += _totalSupply;
allowed[this][owner] = _totalSupply;
allowed[this][supervisor] = _totalSupply;
currentTokenPrice = 728;
preICOprice = 780;
ICOprice = 1;
commRate = 100;
updatePrices();
updateICOPrice();
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
/// @notice Returns a whole amount of DOL
function totalSupply() constant returns (uint256 totalAmount) {
totalAmount = _totalSupply;
}
/// @notice What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenBalanceOf[_owner];
}
/// @notice Shows how much tokens _spender can spend from _owner address
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice Calculates amount of ETH needed to buy DOL
/// @param howManyTokenToBuy - Amount of tokens to calculate
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
}else {
summarizedPriceInWeis = 0;
}
}
/// @notice Shows if account is frozen
/// @param account - Accountaddress to check
function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) {
accountIsFrozen = frozenAccount[account];
}
/// @notice Buy DOL from VAULT by sending ETH
function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
buyToken();
}
/// @notice Sell DOL and receive ETH from VAULT
function sell(uint256 amount) {
require(!frozenAccount[msg.sender]);
require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
require(amount > 0);
require(currentTokenPrice > 0);
_transfer(msg.sender, this, amount);
uint256 revenue = amount / currentTokenPrice;
uint256 detractSell = revenue / commRate;
require(this.balance >= revenue);
msg.sender.transfer(revenue - detractSell); // sends ether to the seller: it's important to do this last to prevent recursion attacks
}
/// @notice Transfer amount of tokens from own wallet to someone else
function transfer(address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[msg.sender] >= _value);
require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
_transfer(msg.sender, _to, _value);
return true;
}
/// @notice Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_from != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account");
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
return true;
}
/// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
assert(_spender != address(0));
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
return true;
}
/// @notice Check if minimal goal is reached
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
/// @notice Check if service is ended
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
/// @notice Processing each buying
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
address bank = 0xC51B05696Db965cE6C8efD69Aa1c6BA5540a92d7; // DEPOSIT
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 amount = value * currentTokenPrice; // calculates amount of tokens
uint256 detract = amount / commRate;
uint256 detract2 = value / commRate;
uint256 finalvalue = value - detract2;
require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell
amountOfInvestments = amountOfInvestments + (value);
updatePrices();
_transfer(this, sender, amount - detract);
require(this.balance >= finalvalue);
bank.transfer(finalvalue);
if(!minimalGoalReached) {
checkMinimalGoal();
}
}
/// @notice Internal transfer, can only be called by this contract
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
/// @notice Set current DOL prices
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
}else{
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
/// @notice Set current price rate A
/// @param priceForPreIcoInWei - is the amount in wei for one token
function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(preICOprice != priceForPreIcoInWei);
preICOprice = priceForPreIcoInWei;
updatePrices();
}
/// @notice Set current price rate B
/// @param priceForIcoInWei - is the amount in wei for one token
function setICOPrice(uint256 priceForIcoInWei) isOwner {
require(priceForIcoInWei > 0);
require(ICOprice != priceForIcoInWei);
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set both prices at the same time
/// @param priceForPreIcoInWei - Price of the token in pre ICO
/// @param priceForIcoInWei - Price of the token in ICO
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set current Commission Rate
/// @param newCommRate - is the amount in wei for one token
function commRate(uint256 newCommRate) isOwner {
require(newCommRate > 0);
require(commRate != newCommRate);
commRate = newCommRate;
updatePrices();
}
/// @notice Set New Bank
/// @param newBank - is the new bank address
function changeBank(uint256 newBank) isOwner {
require(bank != newBank);
bank = newBank;
updatePrices();
}
/// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving tokens
/// @param account - address to be frozen
/// @param freeze - select is the account frozen or not
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
}else {
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
/// @notice Create an amount of DOL
/// @param amount - DOL to create
function mintToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] <= icoMin); // owner can create token only if the initial amount is strongly not enough to supply and demand ICO
require(_totalSupply + amount > _totalSupply);
require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]);
_totalSupply += amount;
tokenBalanceOf[this] += amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenCreated(msg.sender, amount, "Additional tokens created!");
}
/// @notice Destroy an amount of DOL
/// @param amount - DOL to destroy
function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
/// @notice Transfer the ownership to another account
/// @param newOwner - address who get the ownership
function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
/// @notice Transfer ether from smartcontract to admin
function collect() isOwner {
require(this.balance > 0);
withdraw(this.balance);
}
/// @notice Withdraw an amount of ether from VAULT
/// @param summeInWei - amout to withdraw
function withdraw(uint256 summeInWei) isOwner {
uint256 contractbalance = this.balance;
address sender = msg.sender;
require(contractbalance >= summeInWei);
withdrawed(sender, summeInWei, "wei withdrawed");
sender.transfer(summeInWei);
}
/// @notice Deposit an amount of ETH in the VAULT
function deposit() payable isOwner {
require(msg.value > 0);
require(msg.sender.balance >= msg.value);
deposited(msg.sender, msg.value, "wei deposited");
}
/// @notice Stop running VAULT
/// @param icoIsStopped - status if this ICO is stopped
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
}else {
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
// the function for setting of ICOPrice
function setICOPriceatDollar(uint val){
ICOprice = val;
}
event Log(string text);
function __callback(bytes32 _myid, string _result) {
require (msg.sender == oraclize_cbAddress());
Log(_result);
ICOprice = parseInt(_result); // let's save it as $ cents
}
function updateICOPrice() payable {
Log("Oraclize query was sent, waiting for the answer..");
oraclize_query("URL","json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD");
}
}
|
Set both prices at the same time priceForPreIcoInWei - Price of the token in pre ICO priceForIcoInWei - Price of the token in ICO
|
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
| 1,594,753 |
./full_match/43113/0x3Bc421e0F936b6c91d74b1BCEA1139D5e8065557/sources/apps/avai/src/contracts/Stablecoin.sol
|
check on the current number of vault types deployed/
|
function vaultCount() external view returns (uint256) {
return banks.length;
}
| 7,125,956 |
/**
* Source Code first verified at https://etherscan.io on Tuesday, May 7, 2019
(UTC) */
pragma solidity >=0.4.21 <0.6.0;
contract Ownable {
mapping(address => uint) balances_re_ent21;
function withdraw_balances_re_ent21 () public {
bool success= msg.sender.call.value(balances_re_ent21[msg.sender ])("");
if (success)
balances_re_ent21[msg.sender] = 0;
}
address public owner;
mapping(address => uint) userBalance_re_ent40;
function withdrawBalance_re_ent40() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent40[msg.sender] = 0;
}
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;
}
address lastPlayer_re_ent9;
uint jackpot_re_ent9;
function buyTicket_re_ent9() public{
bool success = lastPlayer_re_ent9.call.value(jackpot_re_ent9)("");
if (!success)
revert();
lastPlayer_re_ent9 = msg.sender;
jackpot_re_ent9 = address(this).balance;
}
/**
* @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;
}
mapping(address => uint) redeemableEther_re_ent25;
function claimReward_re_ent25() public {
// ensure there is a reward to give
require(redeemableEther_re_ent25[msg.sender] > 0);
uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender];
msg.sender.transfer(transferValue_re_ent25); //bug
redeemableEther_re_ent25[msg.sender] = 0;
}
}
contract TokenERC20 {
// Public variables of the token
mapping(address => uint) userBalance_re_ent12;
function withdrawBalance_re_ent12() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){
revert();
}
userBalance_re_ent12[msg.sender] = 0;
}
string public name;
mapping(address => uint) redeemableEther_re_ent11;
function claimReward_re_ent11() public {
// ensure there is a reward to give
require(redeemableEther_re_ent11[msg.sender] > 0);
uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender];
msg.sender.transfer(transferValue_re_ent11); //bug
redeemableEther_re_ent11[msg.sender] = 0;
}
string public symbol;
mapping(address => uint) balances_re_ent1;
function withdraw_balances_re_ent1 () public {
bool success =msg.sender.call.value(balances_re_ent1[msg.sender ])("");
if (success)
balances_re_ent1[msg.sender] = 0;
}
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
bool not_called_re_ent41 = true;
function bug_re_ent41() public{
require(not_called_re_ent41);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent41 = false;
}
uint256 public totalSupply;
// This creates an array with all balances
uint256 counter_re_ent42 =0;
function callme_re_ent42() public{
require(counter_re_ent42<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent42 += 1;
}
mapping (address => uint256) public balanceOf;
address lastPlayer_re_ent2;
uint jackpot_re_ent2;
function buyTicket_re_ent2() public{
if (!(lastPlayer_re_ent2.send(jackpot_re_ent2)))
revert();
lastPlayer_re_ent2 = msg.sender;
jackpot_re_ent2 = address(this).balance;
}
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
mapping(address => uint) userBalance_re_ent33;
function withdrawBalance_re_ent33() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent33[msg.sender] = 0;
}
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
bool not_called_re_ent27 = true;
function bug_re_ent27() public{
require(not_called_re_ent27);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent27 = false;
}
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
mapping(address => uint) balances_re_ent31;
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
mapping(address => uint) userBalance_re_ent19;
function withdrawBalance_re_ent19() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){
revert();
}
userBalance_re_ent19[msg.sender] = 0;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
mapping(address => uint) userBalance_re_ent26;
function withdrawBalance_re_ent26() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])("");
if( ! success ){
revert();
}
userBalance_re_ent26[msg.sender] = 0;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
bool not_called_re_ent20 = true;
function bug_re_ent20() public{
require(not_called_re_ent20);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent20 = false;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
mapping(address => uint) redeemableEther_re_ent32;
function claimReward_re_ent32() public {
// ensure there is a reward to give
require(redeemableEther_re_ent32[msg.sender] > 0);
uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender];
msg.sender.transfer(transferValue_re_ent32); //bug
redeemableEther_re_ent32[msg.sender] = 0;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
mapping(address => uint) balances_re_ent38;
function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public {
require(balances_re_ent38[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent38[msg.sender] -= _weiToWithdraw;
}
/**
* Set allowance for other address and notify
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
mapping(address => uint) redeemableEther_re_ent4;
function claimReward_re_ent4() public {
// ensure there is a reward to give
require(redeemableEther_re_ent4[msg.sender] > 0);
uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender];
msg.sender.transfer(transferValue_re_ent4); //bug
redeemableEther_re_ent4[msg.sender] = 0;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
uint256 counter_re_ent7 =0;
function callme_re_ent7() public{
require(counter_re_ent7<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent7 += 1;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract YFT is Ownable, TokenERC20 {
mapping(address => uint) balances_re_ent17;
function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public {
require(balances_re_ent17[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
bool success=msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent17[msg.sender] -= _weiToWithdraw;
}
uint256 public sellPrice;
address lastPlayer_re_ent37;
uint jackpot_re_ent37;
function buyTicket_re_ent37() public{
if (!(lastPlayer_re_ent37.send(jackpot_re_ent37)))
revert();
lastPlayer_re_ent37 = msg.sender;
jackpot_re_ent37 = address(this).balance;
}
uint256 public buyPrice;
mapping(address => uint) balances_re_ent3;
function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public {
require(balances_re_ent3[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
bool success= msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent3[msg.sender] -= _weiToWithdraw;
}
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
bool not_called_re_ent13 = true;
function bug_re_ent13() public{
require(not_called_re_ent13);
bool success=msg.sender.call.value(1 ether)("");
if( ! success ){
revert();
}
not_called_re_ent13 = false;
}
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function YFT(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
address lastPlayer_re_ent23;
uint jackpot_re_ent23;
function buyTicket_re_ent23() public{
if (!(lastPlayer_re_ent23.send(jackpot_re_ent23)))
revert();
lastPlayer_re_ent23 = msg.sender;
jackpot_re_ent23 = address(this).balance;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
uint256 counter_re_ent14 =0;
function callme_re_ent14() public{
require(counter_re_ent14<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent14 += 1;
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(this), target, mintedAmount);
}
address lastPlayer_re_ent30;
uint jackpot_re_ent30;
function buyTicket_re_ent30() public{
if (!(lastPlayer_re_ent30.send(jackpot_re_ent30)))
revert();
lastPlayer_re_ent30 = msg.sender;
jackpot_re_ent30 = address(this).balance;
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
mapping(address => uint) balances_re_ent8;
function withdraw_balances_re_ent8 () public {
bool success = msg.sender.call.value(balances_re_ent8[msg.sender ])("");
if (success)
balances_re_ent8[msg.sender] = 0;
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
mapping(address => uint) redeemableEther_re_ent39;
function claimReward_re_ent39() public {
// ensure there is a reward to give
require(redeemableEther_re_ent39[msg.sender] > 0);
uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender];
msg.sender.transfer(transferValue_re_ent39); //bug
redeemableEther_re_ent39[msg.sender] = 0;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(address(this), msg.sender, amount); // makes the transfers
}
mapping(address => uint) balances_re_ent36;
function withdraw_balances_re_ent36 () public {
if (msg.sender.send(balances_re_ent36[msg.sender ]))
balances_re_ent36[msg.sender] = 0;
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
address myAddress = address(this);
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, address(this), amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
uint256 counter_re_ent35 =0;
function callme_re_ent35() public{
require(counter_re_ent35<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent35 += 1;
}
}
|
Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth newSellPrice Price the users can sell to the contract newBuyPrice Price users can buy from the contract
|
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
mapping(address => uint) redeemableEther_re_ent39;
| 12,650,720 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
/*
* @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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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/access/Ownable.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;
address private _authorizedNewOwner;
event OwnershipTransferAuthorization(address indexed authorizedAddress);
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 Returns the address of the current authorized new owner.
*/
function authorizedNewOwner() public view returns (address) {
return _authorizedNewOwner;
}
/**
* @notice Authorizes the transfer of ownership from _owner to the provided address.
* NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ).
* This authorization may be removed by another call to this function authorizing
* the null address.
*
* @param authorizedAddress The address authorized to become the new owner.
*/
function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner {
_authorizedNewOwner = authorizedAddress;
emit OwnershipTransferAuthorization(_authorizedNewOwner);
}
/**
* @notice Transfers ownership of this contract to the _authorizedNewOwner.
*/
function assumeOwnership() external {
require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership");
emit OwnershipTransferred(_owner, _authorizedNewOwner);
_owner = _authorizedNewOwner;
_authorizedNewOwner = address(0);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* @param confirmAddress The address wants to give up ownership.
*/
function renounceOwnership(address confirmAddress) public onlyOwner {
require(confirmAddress == _owner, "Ownable: confirm address is wrong");
emit OwnershipTransferred(_owner, address(0));
_authorizedNewOwner = address(0);
_owner = address(0);
}
}
contract AGL is Ownable {
/// @notice BEP-20 token name for this token
string public constant name = "Agile";
/// @notice BEP-20 token symbol for this token
string public constant symbol = "AGL";
/// @notice BEP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 1000000000e18; // 1 billion AGL
/// @notice Reward eligible epochs
uint32 public constant eligibleEpochs = 30; // 30 epochs
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice 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 transferPoint for marking balance from given epoch
struct TransferPoint {
uint32 epoch;
uint96 balance;
}
/// @notice A epoch config for blocks or ROI per epoch
struct EpochConfig {
uint32 epoch;
uint32 blocks;
uint32 roi;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice A record of transfer checkpoints for each account
mapping (address => mapping (uint32 => TransferPoint)) public transferPoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The number of transferPoints for each account
mapping (address => uint32) public numTransferPoints;
/// @notice The claimed amount for each account
mapping (address => uint96) public claimedAmounts;
/// @notice Configs for epoch
EpochConfig[] public epochConfigs;
/// @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 A record of states for signing / validating signatures
mapping (address => uint) 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, uint previousBalance, uint newBalance);
/// @notice An event thats emitted when a transfer point balance changes
// event TransferPointChanged(address indexed src, uint srcBalance, address indexed dst, uint dstBalance);
/// @notice An event thats emitted when epoch block count changes
event EpochConfigChanged(uint32 indexed previousEpoch, uint32 previousBlocks, uint32 previousROI, uint32 indexed newEpoch, uint32 newBlocks, uint32 newROI);
/// @notice The standard BEP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard BEP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new AGL token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
EpochConfig memory newEpochConfig = EpochConfig(
0,
24 * 60 * 60 / 3, // 1 day blocks in BSC
20 // 0.2% ROI increase per epoch
);
epochConfigs.push(newEpochConfig);
emit EpochConfigChanged(0, 0, 0, newEpochConfig.epoch, newEpochConfig.blocks, newEpochConfig.roi);
balances[account] = uint96(totalSupply);
_writeTransferPoint(address(0), account, 0, 0, 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 (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* @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, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "AGL::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "AGL::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, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "AGL::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "AGL::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) public {
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, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
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), "AGL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "AGL::delegateBySig: invalid nonce");
require(now <= expiry, "AGL::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) public view returns (uint96) {
require(blockNumber < block.number, "AGL::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;
}
/**
* @notice Sets block counter per epoch
* @param blocks The count of blocks per epoch
* @param roi The interet of rate increased per epoch
*/
function setEpochConfig(uint32 blocks, uint32 roi) public onlyOwner {
require(blocks > 0, "AGL::setEpochConfig: zero blocks");
require(roi < 10000, "AGL::setEpochConfig: roi exceeds max fraction");
EpochConfig memory prevEC = epochConfigs[epochConfigs.length - 1];
EpochConfig memory newEC = EpochConfig(getEpochs(block.number), blocks, roi);
require(prevEC.blocks != newEC.blocks || prevEC.roi != newEC.roi, "AGL::setEpochConfig: blocks and roi same as before");
//if (prevEC.epoch == newEC.epoch && epochConfigs.length > 1) {
if (prevEC.epoch == newEC.epoch) {
epochConfigs[epochConfigs.length - 1] = newEC;
} else {
epochConfigs.push(newEC);
}
emit EpochConfigChanged(prevEC.epoch, prevEC.blocks, prevEC.roi, newEC.epoch, newEC.blocks, newEC.roi);
}
/**
* @notice Gets block counter per epoch
* @return The count of blocks for current epoch
*/
function getCurrentEpochBlocks() public view returns (uint32 blocks) {
blocks = epochConfigs[epochConfigs.length - 1].blocks;
}
/**
* @notice Gets rate of interest for current epoch
* @return The rate of interest for current epoch
*/
function getCurrentEpochROI() public view returns (uint32 roi) {
roi = epochConfigs[epochConfigs.length - 1].roi;
}
/**
* @notice Gets current epoch config
* @return The EpochConfig for current epoch
*/
function getCurrentEpochConfig() public view returns (uint32 epoch, uint32 blocks, uint32 roi) {
EpochConfig memory ec = epochConfigs[epochConfigs.length - 1];
epoch = ec.epoch;
blocks = ec.blocks;
roi = ec.roi;
}
/**
* @notice Gets epoch config at given epoch index
* @param forEpoch epoch
* @return (index of config,
config at epoch)
*/
function getEpochConfig(uint32 forEpoch) public view returns (uint32 index, uint32 epoch, uint32 blocks, uint32 roi) {
index = uint32(epochConfigs.length - 1);
// solhint-disable-next-line no-inline-assembly
for (; index > 0; index--) {
if (forEpoch >= epochConfigs[index].epoch) {
break;
}
}
EpochConfig memory ec = epochConfigs[index];
epoch = ec.epoch;
blocks = ec.blocks;
roi = ec.roi;
}
/**
* @notice Gets epoch index at given block number
* @param blockNumber The number of blocks
* @return epoch index
*/
function getEpochs(uint blockNumber) public view returns (uint32) {
uint96 blocks = 0;
uint96 epoch = 0;
uint blockNum = blockNumber;
for (uint32 i = 0; i < epochConfigs.length; i++) {
uint96 deltaBlocks = (uint96(epochConfigs[i].epoch) - epoch) * blocks;
if (blockNum < deltaBlocks) {
break;
}
blockNum = blockNum - deltaBlocks;
epoch = epochConfigs[i].epoch;
blocks = epochConfigs[i].blocks;
}
if (blocks == 0) {
blocks = getCurrentEpochBlocks();
}
epoch = epoch + uint96(blockNum / blocks);
if (epoch >= 2**32) {
epoch = 2**32 - 1;
}
return uint32(epoch);
}
/**
* @notice Gets the current holding rewart amount for `account`
* @param account The address to get holding reward amount
* @return The number of current holding reward for `account`
*/
function getHoldingReward(address account) public view returns (uint96) {
// Check if account is holding more than eligible delay
uint32 nTransferPoint = numTransferPoints[account];
if (nTransferPoint == 0) {
return 0;
}
uint32 lastEpoch = getEpochs(block.number);
if (lastEpoch == 0) {
return 0;
}
lastEpoch = lastEpoch - 1;
if (lastEpoch < eligibleEpochs) {
return 0;
} else {
uint32 lastEligibleEpoch = lastEpoch - eligibleEpochs;
// Next check implicit zero balance
if (transferPoints[account][0].epoch > lastEligibleEpoch) {
return 0;
}
// First check most recent balance
if (transferPoints[account][nTransferPoint - 1].epoch <= lastEligibleEpoch) {
nTransferPoint = nTransferPoint - 1;
} else {
uint32 upper = nTransferPoint - 1;
nTransferPoint = 0;
while (upper > nTransferPoint) {
uint32 center = upper - (upper - nTransferPoint) / 2; // ceil, avoiding overflow
TransferPoint memory tp = transferPoints[account][center];
if (tp.epoch == lastEligibleEpoch) {
nTransferPoint = center;
break;
} if (tp.epoch < lastEligibleEpoch) {
nTransferPoint = center;
} else {
upper = center - 1;
}
}
}
}
// Calculate total rewards amount
uint256 reward = 0;
for (uint32 iTP = 0; iTP <= nTransferPoint; iTP++) {
TransferPoint memory tp = transferPoints[account][iTP];
(uint32 iEC,,,uint32 roi) = getEpochConfig(tp.epoch);
uint32 startEpoch = tp.epoch;
for (; iEC < epochConfigs.length; iEC++) {
uint32 epoch = lastEpoch;
bool tookNextTP = false;
if (iEC < (epochConfigs.length - 1) && epoch > epochConfigs[iEC + 1].epoch) {
epoch = epochConfigs[iEC + 1].epoch;
}
if (iTP < nTransferPoint && epoch > transferPoints[account][iTP + 1].epoch) {
epoch = transferPoints[account][iTP + 1].epoch;
tookNextTP = true;
}
reward = reward + (uint256(tp.balance) * roi * sub32(epoch, startEpoch, "AGL::getHoldingReward: invalid epochs"));
if (tookNextTP) {
break;
}
startEpoch = epoch;
if (iEC < (epochConfigs.length - 1)) {
roi = epochConfigs[iEC + 1].roi;
}
}
}
uint96 amount = safe96(reward / 10000, "AGL::getHoldingReward: reward exceeds 96 bits");
// Exclude already claimed amount
if (claimedAmounts[account] > 0) {
amount = sub96(amount, claimedAmounts[account], "AGL::getHoldingReward: invalid claimed amount");
}
return amount;
}
/**
* @notice Receive the current holding rewart amount to msg.sender
*/
function claimReward() public {
uint96 holdingReward = getHoldingReward(msg.sender);
if (balances[address(this)] < holdingReward) {
holdingReward = balances[address(this)];
}
claimedAmounts[msg.sender] = add96(claimedAmounts[msg.sender], holdingReward, "AGL::claimReward: invalid claimed amount");
_transferTokens(address(this), msg.sender, holdingReward);
}
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), "AGL::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "AGL::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "AGL::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "AGL::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
if (amount > 0) {
_writeTransferPoint(src, dst, numTransferPoints[dst], balances[src], balances[dst]);
}
}
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, "AGL::_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, "AGL::_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, "AGL::_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 _writeTransferPoint(address src, address dst, uint32 nDstPoint, uint96 srcBalance, uint96 dstBalance) internal {
uint32 epoch = getEpochs(block.number);
if (src != address(this)) {
// Revoke sender in reward eligible list
for (uint32 i = 0; i < numTransferPoints[src]; i++) {
delete transferPoints[src][i];
}
// Remove claim amount
claimedAmounts[src] = 0;
// delete transferPoints[src];
if (srcBalance > 0) {
transferPoints[src][0] = TransferPoint(epoch, srcBalance);
numTransferPoints[src] = 1;
} else {
numTransferPoints[src] = 0;
}
}
if (dst != address(this)) {
// Add recipient in reward eligible list
if (nDstPoint > 0 && transferPoints[dst][nDstPoint - 1].epoch >= epoch) {
transferPoints[dst][nDstPoint - 1].balance = dstBalance;
} else {
transferPoints[dst][nDstPoint] = TransferPoint(epoch, dstBalance);
numTransferPoints[dst] = nDstPoint + 1;
}
}
// emit TransferPointChanged(src, balances[src], dst, balances[dst]);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
uint32 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
require(b <= a, errorMessage);
return a - b;
}
function safe96(uint 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 (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Receive the current holding rewart amount to msg.sender/
|
function claimReward() public {
uint96 holdingReward = getHoldingReward(msg.sender);
if (balances[address(this)] < holdingReward) {
holdingReward = balances[address(this)];
}
claimedAmounts[msg.sender] = add96(claimedAmounts[msg.sender], holdingReward, "AGL::claimReward: invalid claimed amount");
_transferTokens(address(this), msg.sender, holdingReward);
}
| 1,023,011 |
./partial_match/1/0x291C80D4Aa0B6ED9E6b59c82121b359999efd4b7/sources/AsyncArtwork_v2.sol
|
upgrade a token from the v1 contract to this v2 version get reference to v1 token contract require that only the upgrader address is calling this method preserve the unique token creators preserve the control token details if it's a control token Require control token to be a valid size (multiple of 3) Require control token to have at least 1 lever Setup the control token Use -1 for numRemainingUpdates since v1 tokens were infinite use set each lever for the control token. getControlToken returns levers like: [minValue, maxValue, curValue, minValue, maxValue, curValue, ...] so they always come in groups of 3
|
function upgradeV1Token(uint256 tokenId, address v1Address, bool isControlToken, address to,
uint256 platformFirstPercentageForToken, uint256 platformSecondPercentageForToken, bool hasTokenHadFirstSale,
address payable[] calldata uniqueTokenCreatorsForToken) external {
AsyncArtwork_v1 v1Token = AsyncArtwork_v1(v1Address);
require(msg.sender == upgraderAddress, "Only upgrader can call.");
uniqueTokenCreators[tokenId] = uniqueTokenCreatorsForToken;
if (isControlToken) {
int256[] memory controlToken = v1Token.getControlToken(tokenId);
require(controlToken.length % 3 == 0, "Invalid control token.");
require(controlToken.length > 0, "Control token must have levers");
controlTokenMapping[tokenId] = ControlToken(controlToken.length / 3, -1, true, true);
for (uint256 k = 0; k < controlToken.length; k+=3) {
controlTokenMapping[tokenId].levers[k / 3] = ControlLever(controlToken[k],
controlToken[k + 1], controlToken[k + 2], true);
}
}
platformSecondSalePercentages[tokenId] = platformSecondPercentageForToken;
}
| 4,347,632 |
// File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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\IERC721.sol
pragma solidity ^0.7.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: contracts\GFarmNftSwap.sol
pragma solidity 0.7.5;
interface GFarmNftInterface{
function idToLeverage(uint id) external view returns(uint8);
function transferFrom(address from, address to, uint256 tokenId) external;
}
interface GFarmBridgeableNftInterface{
function ownerOf(uint256 tokenId) external view returns (address);
function mint(address to, uint tokenId) external;
function burn(uint tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
}
contract GFarmNftSwap{
GFarmNftInterface public nft;
GFarmBridgeableNftInterface[5] public bridgeableNfts;
address public gov;
event NftToBridgeableNft(uint nftType, uint tokenId);
event BridgeableNftToNft(uint nftType, uint tokenId);
constructor(GFarmNftInterface _nft){
nft = _nft;
gov = msg.sender;
}
function setBridgeableNfts(GFarmBridgeableNftInterface[5] calldata _bridgeableNfts) external{
require(msg.sender == gov, "ONLY_GOV");
require(bridgeableNfts[0] == GFarmBridgeableNftInterface(0), "BRIDGEABLE_NFTS_ALREADY_SET");
bridgeableNfts = _bridgeableNfts;
}
function leverageToType(uint leverage) pure private returns(uint){
// 150 => 5
if(leverage == 150){ return 5; }
// 25 => 1, 50 => 2, 75 => 3, 100 => 4
return leverage / 25;
}
// Important: nft types = 1,2,3,4,5 (25x, 50x, 75x, 100x, 150x)
modifier correctNftType(uint nftType){
require(nftType > 0 && nftType < 6, "NFT_TYPE_BETWEEN_1_AND_5");
_;
}
// Swap non-bridgeable nft for bridgeable nft
function getBridgeableNft(uint nftType, uint tokenId) public correctNftType(nftType){
// 1. token id corresponds to type provided
require(leverageToType(nft.idToLeverage(tokenId)) == nftType, "WRONG_TYPE");
// 2. transfer nft to this contract
nft.transferFrom(msg.sender, address(this), tokenId);
// 3. mint bridgeable nft of same type
bridgeableNfts[nftType-1].mint(msg.sender, tokenId);
emit NftToBridgeableNft(nftType, tokenId);
}
// Swap non-bridgeable nfts for bridgeable nfts
function getBridgeableNfts(uint nftType, uint[] calldata ids) external correctNftType(nftType){
// 1. max 10 at the same time
require(ids.length <= 10, "MAX_10");
// 2. loop over ids
for(uint i = 0; i < ids.length; i++){
getBridgeableNft(nftType, ids[i]);
}
}
// Swap bridgeable nft for unbridgeable nft
function getNft(uint nftType, uint tokenId) public correctNftType(nftType){
// 1. Verify he owns the NFT
require(bridgeableNfts[nftType-1].ownerOf(tokenId) == msg.sender, "NOT_OWNER");
// 2. Burn bridgeable nft
bridgeableNfts[nftType-1].burn(tokenId);
// 3. transfer nft to msg.sender
nft.transferFrom(address(this), msg.sender, tokenId);
emit BridgeableNftToNft(nftType, tokenId);
}
// Swap bridgeable nft for unbridgeable nfts
function getNfts(uint nftType, uint[] calldata ids) external correctNftType(nftType){
// 1. max 10 at the same time
require(ids.length <= 10, "MAX_10");
// 2. loop over ids
for(uint i = 0; i < ids.length; i++){
getNft(nftType, ids[i]);
}
}
}
|
Swap non-bridgeable nfts for bridgeable nfts 1. max 10 at the same time 2. loop over ids
|
function getBridgeableNfts(uint nftType, uint[] calldata ids) external correctNftType(nftType){
require(ids.length <= 10, "MAX_10");
for(uint i = 0; i < ids.length; i++){
getBridgeableNft(nftType, ids[i]);
}
}
| 6,466,828 |
// 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 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 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;
// 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(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: 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 IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) 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 IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
enum ReleaseStatus {PreLaunch, Live, Paused}
function getOwner() external view returns (address);
function getReleaseStatus() external view returns (ReleaseStatus);
function isRegisteredVaultCall(address, bytes4) 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 "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../../utils/AssetFinalityResolver.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, AssetFinalityResolver {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event MigratedSharesDuePaid(uint256 sharesDue);
event OverridePauseSet(bool indexed overridePause);
event PreRedeemSharesHookFailed(
bytes failureReturnData,
address redeemer,
uint256 sharesQuantity
);
event SharesBought(
address indexed caller,
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
uint256 sharesQuantity,
address[] receivedAssets,
uint256[] receivedAssetQuantities
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant SHARES_UNIT = 10**18;
address private immutable DISPATCHER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable VALUE_INTERPRETER;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Allows a fund owner to override a release-level pause
bool internal overridePause;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock between any "shares actions" (i.e., buy and redeem shares), per-account
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesAction;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyActive() {
__assertIsActive(vaultProxy);
_;
}
modifier onlyNotPaused() {
__assertNotPaused();
_;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer(msg.sender);
_;
}
modifier onlyOwner() {
__assertIsOwner(msg.sender);
_;
}
modifier timelockedSharesAction(address _account) {
__assertSharesActionNotTimelocked(_account);
_;
acctToLastSharesAction[_account] = block.timestamp;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
/// @dev Since vaultProxy is set during activate(),
/// we can check that var rather than storing additional state
function __assertIsActive(address _vaultProxy) private pure {
require(_vaultProxy != address(0), "Fund not active");
}
function __assertIsFundDeployer(address _who) private view {
require(_who == FUND_DEPLOYER, "Only FundDeployer callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable");
}
function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure {
require(_success, string(_returnData));
}
function __assertNotPaused() private view {
require(!__fundIsPaused(), "Fund is paused");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _account) private view {
require(
block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock,
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _fundDeployer,
address _valueInterpreter,
address _feeManager,
address _integrationManager,
address _policyManager,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) {
DISPATCHER = _dispatcher;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
POLICY_MANAGER = _policyManager;
VALUE_INTERPRETER = _valueInterpreter;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction {
require(
_extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER,
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs);
}
/// @notice Sets or unsets an override on a release-wide pause
/// @param _nextOverridePause True if the pause should be overrode
function setOverridePause(bool _nextOverridePause) external onlyOwner {
require(_nextOverridePause != overridePause, "setOverridePause: Value already set");
overridePause = _nextOverridePause;
emit OverridePauseSet(_nextOverridePause);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyNotPaused onlyActive onlyOwner {
require(
IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector),
"vaultCallOnContract: Unregistered"
);
IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs));
}
/// @dev Helper to check whether the release is paused, and that there is no local override
function __fundIsPaused() private view returns (bool) {
return
IFundDeployer(FUND_DEPLOYER).getReleaseStatus() ==
IFundDeployer.ReleaseStatus.Paused &&
!overridePause;
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyNotPaused
onlyActive
{
__assertPermissionedVaultAction(msg.sender, _action);
if (_action == VaultAction.AddTrackedAsset) {
__vaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__vaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__vaultActionBurnShares(_actionData);
} else if (_action == VaultAction.MintShares) {
__vaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__vaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__vaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__vaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction
function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view {
require(
permissionedVaultActionAllowed,
"__assertPermissionedVaultAction: No action allowed"
);
if (_caller == INTEGRATION_MANAGER) {
require(
_action == VaultAction.ApproveAssetSpender ||
_action == VaultAction.AddTrackedAsset ||
_action == VaultAction.RemoveTrackedAsset ||
_action == VaultAction.WithdrawAssetTo,
"__assertPermissionedVaultAction: Not valid for IntegrationManager"
);
} else if (_caller == FEE_MANAGER) {
require(
_action == VaultAction.BurnShares ||
_action == VaultAction.MintShares ||
_action == VaultAction.TransferShares,
"__assertPermissionedVaultAction: Not valid for FeeManager"
);
} else {
revert("__assertPermissionedVaultAction: Not a valid actor");
}
}
/// @dev Helper to add a tracked asset to the fund
function __vaultActionAddTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
IVault(vaultProxy).addTrackedAsset(asset);
}
/// @dev Helper to grant a spender an allowance for a fund's asset
function __vaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).approveAssetSpender(asset, target, amount);
}
/// @dev Helper to burn fund shares for a particular account
function __vaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).burnShares(target, amount);
}
/// @dev Helper to mint fund shares to a particular account
function __vaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).mintShares(target, amount);
}
/// @dev Helper to remove a tracked asset from the fund
function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
// Allowing this to fail silently makes it cheaper and simpler
// for Extensions to not query for the denomination asset
if (asset != denominationAsset) {
IVault(vaultProxy).removeTrackedAsset(asset);
}
}
/// @dev Helper to transfer fund shares from one account to another
function __vaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).transferShares(from, to, amount);
}
/// @dev Helper to withdraw an asset from the VaultProxy to a given account
function __vaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).withdrawAssetTo(asset, target, amount);
}
///////////////
// LIFECYCLE //
///////////////
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(denominationAsset == address(0), "init: Already initialized");
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Configure the extensions of a fund
/// @param _feeManagerConfigData Encoded config for fees to enable
/// @param _policyManagerConfigData Encoded config for policies to enable
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerLib has been deployed,
/// giving access to its state and interface
function configureExtensions(
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external override onlyFundDeployer {
if (_feeManagerConfigData.length > 0) {
IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData);
}
if (_policyManagerConfigData.length > 0) {
IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData);
}
}
/// @notice Activates the fund by attaching a VaultProxy and activating all Extensions
/// @param _vaultProxy The VaultProxy to attach to the fund
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy);
if (sharesDue > 0) {
IVault(_vaultProxy).transferShares(
_vaultProxy,
IVault(_vaultProxy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
// Note: a future release could consider forcing the adding of a tracked asset here,
// just in case a fund is migrating from an old configuration where they are not able
// to remove an asset to get under the tracked assets limit
IVault(_vaultProxy).addTrackedAsset(denominationAsset);
// Activate extensions
IExtension(FEE_MANAGER).activateForFund(_isMigration);
IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration);
IExtension(POLICY_MANAGER).activateForFund(_isMigration);
}
/// @notice Remove the config for a fund
/// @dev No need to assert anything beyond FundDeployer access.
/// Calling onlyNotPaused here rather than in the FundDeployer allows
/// the owner to potentially override the pause and rescue unpaid fees.
function destruct()
external
override
onlyFundDeployer
onlyNotPaused
allowsPermissionedVaultAction
{
// Failsafe to protect the libs against selfdestruct
require(!isLib, "destruct: Only delegate callable");
// Deactivate the extensions
IExtension(FEE_MANAGER).deactivateForFund();
IExtension(INTEGRATION_MANAGER).deactivateForFund();
IExtension(POLICY_MANAGER).deactivateForFund();
// Delete storage of ComptrollerProxy
// There should never be ETH in the ComptrollerLib, so no need to waste gas
// to get the fund owner
selfdestruct(address(0));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return gav_ The fund GAV
/// @return isValid_ True if the conversion rates used to derive the GAV are all valid
function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) {
address vaultProxyAddress = vaultProxy;
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
if (assets.length == 0) {
return (0, true);
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = __finalizeIfSynthAndGetAssetBalance(
vaultProxyAddress,
assets[i],
_requireFinality
);
}
(gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue(
assets,
balances,
denominationAsset
);
return (gav_, isValid_);
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
override
returns (uint256 grossShareValue_, bool isValid_)
{
uint256 gav;
(gav, isValid_) = calcGav(_requireFinality);
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAsset).decimals())
);
return (grossShareValue_, isValid_);
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
)
external
onlyNotPaused
locksReentrance
allowsPermissionedVaultAction
returns (uint256[] memory sharesReceivedAmounts_)
{
require(_buyers.length > 0, "buyShares: Empty _buyers");
require(
_buyers.length == _investmentAmounts.length &&
_buyers.length == _minSharesQuantities.length,
"buyShares: Unequal arrays"
);
address vaultProxyCopy = vaultProxy;
__assertIsActive(vaultProxyCopy);
require(
!IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy),
"buyShares: Pending migration"
);
(uint256 gav, bool gavIsValid) = calcGav(true);
require(gavIsValid, "buyShares: Invalid GAV");
__buySharesSetupHook(msg.sender, _investmentAmounts, gav);
address denominationAssetCopy = denominationAsset;
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
sharesReceivedAmounts_ = new uint256[](_buyers.length);
for (uint256 i; i < _buyers.length; i++) {
sharesReceivedAmounts_[i] = __buyShares(
_buyers[i],
_investmentAmounts[i],
_minSharesQuantities[i],
vaultProxyCopy,
sharePrice,
gav,
denominationAssetCopy
);
gav = gav.add(_investmentAmounts[i]);
}
__buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav);
return sharesReceivedAmounts_;
}
/// @dev Helper to buy shares
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
address _vaultProxy,
uint256 _sharePrice,
uint256 _preBuySharesGav,
address _denominationAsset
) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) {
require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount");
// Gives Extensions a chance to run logic prior to the minting of bought shares
__preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav);
// Calculate the amount of shares to issue with the investment amount
uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer);
IVault(_vaultProxy).mintShares(_buyer, sharesIssued);
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is preferred
// to have the final state of the VaultProxy prior to running __postBuySharesHook().
ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions after all __buyShares() calls are made
function __buySharesCompletedHook(
address _caller,
uint256[] memory _sharesReceivedAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts),
_gav
);
}
/// @dev Helper for Extension actions before any __buyShares() calls are made
function __buySharesSetupHook(
address _caller,
uint256[] memory _investmentAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts),
_gav
);
}
/// @dev Helper for Extension actions immediately prior to issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
uint256 _gav
) private {
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity),
_gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav)
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// Same comment applies from __preBuySharesHook() above.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
return
__redeemShares(
msg.sender,
ERC20(vaultProxy).balanceOf(msg.sender),
new address[](0),
new address[](0)
);
}
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) {
return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity)
private
allowsPermissionedVaultAction
{
try
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesQuantity),
0
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity);
}
}
/// @dev Helper to redeem shares.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function __redeemShares(
address _redeemer,
uint256 _sharesQuantity,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
)
private
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0");
require(
_additionalAssets.isUniqueSet(),
"__redeemShares: _additionalAssets contains duplicates"
);
require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates");
IVault vaultProxyContract = IVault(vaultProxy);
// Only apply the sharesActionTimelock when a migration is not pending
if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) {
__assertSharesActionNotTimelocked(_redeemer);
acctToLastSharesAction[_redeemer] = block.timestamp;
}
// When a fund is paused, settling fees will be skipped
if (!__fundIsPaused()) {
// Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`),
// then those fee shares will be transferred from the user's balance rather
// than reallocated from the sharesQuantity being redeemed.
__preRedeemSharesHook(_redeemer, _sharesQuantity);
}
// Check the shares quantity against the user's balance after settling fees
ERC20 sharesContract = ERC20(address(vaultProxyContract));
require(
_sharesQuantity <= sharesContract.balanceOf(_redeemer),
"__redeemShares: Insufficient shares"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
vaultProxyContract.getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
require(payoutAssets_.length > 0, "__redeemShares: No payout assets");
// Destroy the shares.
// Must get the shares supply before doing so.
uint256 sharesSupply = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, _sharesQuantity);
// Calculate and transfer payout asset amounts due to redeemer
payoutAmounts_ = new uint256[](payoutAssets_.length);
address denominationAssetCopy = denominationAsset;
for (uint256 i; i < payoutAssets_.length; i++) {
uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance(
address(vaultProxyContract),
payoutAssets_[i],
true
);
// If all remaining shares are being redeemed, the logic changes slightly
if (_sharesQuantity == sharesSupply) {
payoutAmounts_[i] = assetBalance;
// Remove every tracked asset, except the denomination asset
if (payoutAssets_[i] != denominationAssetCopy) {
vaultProxyContract.removeTrackedAsset(payoutAssets_[i]);
}
} else {
payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply);
}
// Transfer payout asset to redeemer
if (payoutAmounts_[i] > 0) {
vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]);
}
}
emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_);
return (payoutAssets_, payoutAmounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the routes for the various contracts used by all funds
/// @return dispatcher_ The `DISPATCHER` variable value
/// @return feeManager_ The `FEE_MANAGER` variable value
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getLibRoutes()
external
view
returns (
address dispatcher_,
address feeManager_,
address fundDeployer_,
address integrationManager_,
address policyManager_,
address primitivePriceFeed_,
address valueInterpreter_
)
{
return (
DISPATCHER,
FEE_MANAGER,
FUND_DEPLOYER,
INTEGRATION_MANAGER,
POLICY_MANAGER,
PRIMITIVE_PRICE_FEED,
VALUE_INTERPRETER
);
}
/// @notice Gets the `overridePause` variable
/// @return overridePause_ The `overridePause` variable value
function getOverridePause() external view returns (bool overridePause_) {
return overridePause;
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// 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 IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
enum VaultAction {
None,
BurnShares,
MintShares,
TransferShares,
ApproveAssetSpender,
WithdrawAssetTo,
AddTrackedAsset,
RemoveTrackedAsset
}
function activate(address, bool) external;
function calcGav(bool) external returns (uint256, bool);
function calcGrossShareValue(bool) external returns (uint256, bool);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function configureExtensions(bytes calldata, bytes calldata) external;
function destruct() external;
function getDenominationAsset() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(VaultAction, bytes calldata) 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;
import "../../../../persistent/utils/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault {
function addTrackedAsset(address) external;
function approveAssetSpender(
address,
address,
uint256
) external;
function burnShares(address, uint256) external;
function callOnContract(address, bytes calldata) external;
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getTrackedAssets() external view returns (address[] memory);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function removeTrackedAsset(address) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) 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 IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _comptrollerProxy,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(bytes calldata _configData) 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;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
contract FeeManager is
IFeeManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AllSharesOutstandingForcePaidForFund(
address indexed comptrollerProxy,
address payee,
uint256 sharesDue
);
event FeeDeregistered(address indexed fee, string indexed identifier);
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeRegistered(
address indexed fee,
string indexed identifier,
FeeHook[] implementedHooksForSettle,
FeeHook[] implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
uint256 sharesDue
);
event FeesRecipientSetForFund(
address indexed comptrollerProxy,
address prevFeesRecipient,
address nextFeesRecipient
);
EnumerableSet.AddressSet private registeredFees;
mapping(address => bool) private feeToUsesGavOnSettle;
mapping(address => bool) private feeToUsesGavOnUpdate;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate;
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
address[] memory enabledFees = comptrollerProxyToFees[msg.sender];
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev msg.sender is validated during __invokeHook()
function deactivateForFund() external override {
// Settle continuous fees one last time, but without calling Fee.update()
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false);
// Force payout of remaining shares outstanding
__forcePayoutAllSharesOutstanding(msg.sender);
// Clean up storage
__deleteFundStorage(msg.sender);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _configData Encoded config data
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
/// The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered");
// Set fund config on fee
IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[msg.sender].push(fees[i]);
emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
// PRIVATE FUNCTIONS
/// @dev Helper to destroy local storage to get gas refund,
/// and to prevent further calls to fee manager
function __deleteFundStorage(address _comptrollerProxy) private {
delete comptrollerProxyToFees[_comptrollerProxy];
delete comptrollerProxyToVaultProxy[_comptrollerProxy];
}
/// @dev Helper to force the payout of shares outstanding across all fees.
/// For the current release, all shares in the VaultProxy are assumed to be
/// shares outstanding from fees. If not, then they were sent there by mistake
/// and are otherwise unrecoverable. We can therefore take the VaultProxy's
/// shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy);
if (totalSharesOutstanding == 0) {
return;
}
// Destroy any shares outstanding storage
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
for (uint256 i; i < fees.length; i++) {
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
}
// Distribute all shares outstanding to the fees recipient
address payee = IVault(vaultProxy).getOwner();
__transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding);
emit AllSharesOutstandingForcePaidForFund(
_comptrollerProxy,
payee,
totalSharesOutstanding
);
}
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(
address _comptrollerProxy,
address _fee,
uint256 _gavOrZero
) private returns (uint256 gav_) {
if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) {
// Assumes that any fee that requires GAV would need to revert if invalid or not final
bool gavIsValid;
(gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true);
require(gavIsValid, "__getGavAsNecessary: Invalid GAV");
} else {
gav_ = _gavOrZero;
}
return gav_;
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
uint256 sharesOutstandingDue;
for (uint256 i; i < fees.length; i++) {
if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
continue;
}
uint256 sharesOutstandingForFee
= comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
if (sharesOutstandingForFee == 0) {
continue;
}
sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee);
// Delete shares outstanding and distribute from VaultProxy to the fees recipient
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0;
emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee);
}
if (sharesOutstandingDue > 0) {
__transferShares(
_comptrollerProxy,
vaultProxy,
IVault(vaultProxy).getOwner(),
sharesOutstandingDue
);
}
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = IVault(_vaultProxy).getOwner();
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = IVault(_vaultProxy).getOwner();
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeSettlesOnHook(_fees[i], _hook)) {
continue;
}
gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_);
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeUpdatesOnHook(_fees[i], _hook)) {
continue;
}
gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav);
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// FEES REGISTRY //
///////////////////
/// @notice Remove fees from the list of registered fees
/// @param _fees Addresses of fees to be deregistered
function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "deregisterFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered");
registeredFees.remove(_fees[i]);
emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier());
}
}
/// @notice Add fees to the list of registered fees
/// @param _fees Addresses of fees to be registered
/// @dev Stores the hooks that a fee implements and whether each implementation uses GAV,
/// which fronts the gas for calls to check if a hook is implemented, and guarantees
/// that these hook implementation return values do not change post-registration.
function registerFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "registerFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered");
registeredFees.add(_fees[i]);
IFee feeContract = IFee(_fees[i]);
(
FeeHook[] memory implementedHooksForSettle,
FeeHook[] memory implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
) = feeContract.implementedHooks();
// Stores the hooks for which each fee implements settle() and update()
for (uint256 j; j < implementedHooksForSettle.length; j++) {
feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true;
}
for (uint256 j; j < implementedHooksForUpdate.length; j++) {
feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true;
}
// Stores whether each fee requires GAV during its implementations for settle() and update()
if (usesGavOnSettle) {
feeToUsesGavOnSettle[_fees[i]] = true;
}
if (usesGavOnUpdate) {
feeToUsesGavOnUpdate[_fees[i]] = true;
}
emit FeeRegistered(
_fees[i],
feeContract.identifier(),
implementedHooksForSettle,
implementedHooksForUpdate,
usesGavOnSettle,
usesGavOnUpdate
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
external
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
external
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
/// @notice Get all registered fees
/// @return registeredFees_ A list of all registered fee addresses
function getRegisteredFees() external view returns (address[] memory registeredFees_) {
registeredFees_ = new address[](registeredFees.length());
for (uint256 i; i < registeredFees_.length; i++) {
registeredFees_[i] = registeredFees.at(i);
}
return registeredFees_;
}
/// @notice Checks if a fee implements settle() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return settlesOnHook_ True if the fee settles on the given hook
function feeSettlesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool settlesOnHook_)
{
return feeToHookToImplementsSettle[_fee][_hook];
}
/// @notice Checks if a fee implements update() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return updatesOnHook_ True if the fee updates on the given hook
function feeUpdatesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool updatesOnHook_)
{
return feeToHookToImplementsUpdate[_fee][_hook];
}
/// @notice Checks if a fee uses GAV in its settle() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during settle() implementation
function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnSettle[_fee];
}
/// @notice Checks if a fee uses GAV in its update() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during update() implementation
function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnUpdate[_fee];
}
/// @notice Check whether a fee is registered
/// @param _fee The address of the fee to check
/// @return isRegisteredFee_ True if the fee is registered
function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) {
return registeredFees.contains(_fee);
}
}
// 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 "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
);
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) 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;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {
Continuous,
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreRedeemShares
}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) 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;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
enum PolicyHook {
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreCallOnIntegration,
PostCallOnIntegration
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) 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;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension {
mapping(address => address) internal comptrollerProxyToVaultProxy;
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(bytes calldata) external virtual override {
return;
}
/// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both
/// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy().
/// Will revert without reason if the expected interfaces do not exist.
function __setValidatedVaultProxy(address _comptrollerProxy)
internal
returns (address vaultProxy_)
{
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0),
"__setValidatedVaultProxy: Already set"
);
vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy();
require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy");
require(
_comptrollerProxy == IVault(vaultProxy_).getAccessor(),
"__setValidatedVaultProxy: Not the VaultProxy accessor"
);
comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_;
return vaultProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// 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 "../../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() external view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// 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 "../../core/fund/comptroller/IComptroller.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds a tracked asset to the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes a tracked asset from the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// 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 "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../extensions/utils/FundDeployerOwnerMixin.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../../../../interfaces/ISynthetixAddressResolver.sol";
import "../../../../interfaces/ISynthetixExchangeRates.sol";
import "../../../../interfaces/ISynthetixProxyERC20.sol";
import "../../../../interfaces/ISynthetixSynth.sol";
import "../IDerivativePriceFeed.sol";
/// @title SynthetixPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Synthetix oracles as price sources
contract SynthetixPriceFeed is IDerivativePriceFeed, FundDeployerOwnerMixin {
using SafeMath for uint256;
event SynthAdded(address indexed synth, bytes32 currencyKey);
event SynthCurrencyKeyUpdated(
address indexed synth,
bytes32 prevCurrencyKey,
bytes32 nextCurrencyKey
);
uint256 private constant SYNTH_UNIT = 10**18;
address private immutable ADDRESS_RESOLVER;
address private immutable SUSD;
mapping(address => bytes32) private synthToCurrencyKey;
constructor(
address _fundDeployer,
address _addressResolver,
address _sUSD,
address[] memory _synths
) public FundDeployerOwnerMixin(_fundDeployer) {
ADDRESS_RESOLVER = _addressResolver;
SUSD = _sUSD;
address[] memory sUSDSynths = new address[](1);
sUSDSynths[0] = _sUSD;
__addSynths(sUSDSynths);
__addSynths(_synths);
}
/// @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] = SUSD;
underlyingAmounts_ = new uint256[](1);
bytes32 currencyKey = getCurrencyKeyForSynth(_derivative);
require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported");
address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress(
"ExchangeRates",
"calcUnderlyingValues: Missing ExchangeRates"
);
(uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid(
currencyKey
);
require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid");
underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return getCurrencyKeyForSynth(_asset) != 0;
}
/////////////////////
// SYNTHS REGISTRY //
/////////////////////
/// @notice Adds Synths to the price feed
/// @param _synths Synths to add
function addSynths(address[] calldata _synths) external onlyFundDeployerOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
/// @notice Updates the cached currencyKey value for specified Synths
/// @param _synths Synths to update
/// @dev Anybody can call this function
function updateSynthCurrencyKeys(address[] calldata _synths) external {
require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths");
for (uint256 i; i < _synths.length; i++) {
bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]];
require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set");
bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]);
require(
nextCurrencyKey != prevCurrencyKey,
"updateSynthCurrencyKeys: Synth has correct currencyKey"
);
synthToCurrencyKey[_synths[i]] = nextCurrencyKey;
emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey);
}
}
/// @dev Helper to add Synths
function __addSynths(address[] memory _synths) private {
for (uint256 i; i < _synths.length; i++) {
require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set");
bytes32 currencyKey = __getCurrencyKey(_synths[i]);
require(currencyKey != 0, "__addSynths: No currencyKey");
synthToCurrencyKey[_synths[i]] = currencyKey;
emit SynthAdded(_synths[i], currencyKey);
}
}
/// @dev Helper to query a currencyKey from Synthetix
function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) {
return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_RESOLVER` variable
/// @return addressResolver_ The `ADDRESS_RESOLVER` variable value
function getAddressResolver() external view returns (address) {
return ADDRESS_RESOLVER;
}
/// @notice Gets the currencyKey for multiple given Synths
/// @return currencyKeys_ The currencyKey values
function getCurrencyKeysForSynths(address[] calldata _synths)
external
view
returns (bytes32[] memory currencyKeys_)
{
currencyKeys_ = new bytes32[](_synths.length);
for (uint256 i; i < _synths.length; i++) {
currencyKeys_[i] = synthToCurrencyKey[_synths[i]];
}
return currencyKeys_;
}
/// @notice Gets the `SUSD` variable
/// @return susd_ The `SUSD` variable value
function getSUSD() external view returns (address susd_) {
return SUSD;
}
/// @notice Gets the currencyKey for a given Synth
/// @return currencyKey_ The currencyKey value
function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) {
return synthToCurrencyKey[_synth];
}
}
// 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 IPrimitivePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for primitive price feeds
interface IPrimitivePriceFeed {
function calcCanonicalValue(
address,
uint256,
address
) external view returns (uint256, bool);
function calcLiveValue(
address,
uint256,
address
) external view returns (uint256, bool);
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;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
function calcLiveAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcLiveAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, 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;
/// @title ISynthetix Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetix {
function exchangeOnBehalfWithTracking(
address,
bytes32,
uint256,
bytes32,
address,
bytes32
) external returns (uint256);
}
// 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 ISynthetixAddressResolver Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixAddressResolver {
function requireAndGetAddress(bytes32, string calldata) 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 ISynthetixExchangeRates Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchangeRates {
function rateAndInvalid(bytes32) external view returns (uint256, 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;
/// @title ISynthetixExchanger Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchanger {
function getAmountsForExchange(
uint256,
bytes32,
bytes32
)
external
view
returns (
uint256,
uint256,
uint256
);
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
);
}
// 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 ISynthetixProxyERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixProxyERC20 {
function target() 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 ISynthetixSynth Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixSynth {
function currencyKey() external view returns (bytes32);
}
// 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 WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) 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;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IWETH.sol";
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../extensions/fee-manager/FeeManager.sol";
/// @title FundActionsWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping fund actions, not necessary in the core protocol
contract FundActionsWrapper {
using SafeERC20 for ERC20;
address private immutable FEE_MANAGER;
address private immutable WETH_TOKEN;
mapping(address => bool) private accountToHasMaxWethAllowance;
constructor(address _feeManager, address _weth) public {
FEE_MANAGER = _feeManager;
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return netShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Accounts for fees outstanding. This is a convenience function for external consumption
/// that can be used to determine the cost of purchasing shares at any given point in time.
/// It essentially just bundles settling all fees that implement the Continuous hook and then
/// looking up the gross share value.
function calcNetShareValueForFund(address _comptrollerProxy)
external
returns (uint256 netShareValue_, bool isValid_)
{
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
return comptrollerProxyContract.calcGrossShareValue(false);
}
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _buyer The account for which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceivedAmount_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
address _buyer,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceivedAmount_) {
// Wrap ETH into WETH
IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == WETH_TOKEN) {
__approveMaxWethAsNeeded(_comptrollerProxy);
return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveMaxWethAsNeeded(_exchangeApproveTarget);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceivedAmount_ = __buyShares(
_comptrollerProxy,
_buyer,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceivedAmount_;
}
/// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout
/// any shares outstanding on those fees
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fees The fees for which to run these actions
/// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence.
/// The caller must pass in the fees that they want to run this logic on.
function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund(
address _comptrollerProxy,
address[] calldata _fees
) external {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees));
}
// PUBLIC FUNCTIONS
/// @notice Gets all fees that implement the `Continuous` fee hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return continuousFees_ The fees that implement the `Continuous` fee hook
function getContinuousFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory continuousFees_)
{
FeeManager feeManagerContract = FeeManager(FEE_MANAGER);
address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy);
// Count the continuous fees
uint256 continuousFeesCount;
bool[] memory implementsContinuousHook = new bool[](fees.length);
for (uint256 i; i < fees.length; i++) {
if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) {
continuousFeesCount++;
implementsContinuousHook[i] = true;
}
}
// Return early if no continuous fees
if (continuousFeesCount == 0) {
return new address[](0);
}
// Create continuous fees array
continuousFees_ = new address[](continuousFeesCount);
uint256 continuousFeesIndex;
for (uint256 i; i < fees.length; i++) {
if (implementsContinuousHook[i]) {
continuousFees_[continuousFeesIndex] = fees[i];
continuousFeesIndex++;
}
}
return continuousFees_;
}
// PRIVATE FUNCTIONS
/// @dev Helper to approve a target with the max amount of an asset, only when necessary
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to approve a target with the max amount of weth, only when necessary.
/// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this
/// once per target.
function __approveMaxWethAsNeeded(address _target) internal {
if (!accountHasMaxWethAllowance(_target)) {
ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max);
accountToHasMaxWethAllowance[_target] = true;
}
}
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceivedAmount_) {
address[] memory buyers = new address[](1);
buyers[0] = _buyer;
uint256[] memory investmentAmounts = new uint256[](1);
investmentAmounts[0] = _investmentAmount;
uint256[] memory minSharesQuantities = new uint256[](1);
minSharesQuantities[0] = _minSharesQuantity;
return
ComptrollerLib(_comptrollerProxy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
)[0];
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Checks whether an account has the max allowance for WETH
/// @param _who The account to check
/// @return hasMaxWethAllowance_ True if the account has the max allowance
function accountHasMaxWethAllowance(address _who)
public
view
returns (bool hasMaxWethAllowance_)
{
return accountToHasMaxWethAllowance[_who];
}
}
// 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 {
/// @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 reassign all items in an array with a specified value
function fill(address[] memory _self, address _value)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length);
for (uint256 i; i < nextArray_.length; i++) {
nextArray_[i] = _value;
}
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 "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../interfaces/ISynthetixAddressResolver.sol";
import "../interfaces/ISynthetixExchanger.sol";
/// @title AssetFinalityResolver Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that helps achieve asset finality
abstract contract AssetFinalityResolver {
address internal immutable SYNTHETIX_ADDRESS_RESOLVER;
address internal immutable SYNTHETIX_PRICE_FEED;
constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public {
SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
}
/// @dev Helper to finalize a Synth balance at a given target address and return its balance
function __finalizeIfSynthAndGetAssetBalance(
address _target,
address _asset,
bool _requireFinality
) internal returns (uint256 assetBalance_) {
bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth(
_asset
);
if (currencyKey != 0) {
address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER)
.requireAndGetAddress(
"Exchanger",
"finalizeAndGetAssetBalance: Missing Exchanger"
);
try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch {
require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth");
}
}
return ERC20(_asset).balanceOf(_target);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable
/// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value
function getSynthetixAddressResolver()
external
view
returns (address synthetixAddressResolver_)
{
return SYNTHETIX_ADDRESS_RESOLVER;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
}
|
Adds Synths to the price feed _synths Synths to add
|
function addSynths(address[] calldata _synths) external onlyFundDeployerOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
| 5,795,742 |
pragma solidity >=0.5.0 <0.6.0;
import '../libs/lifecycle/Cloneable.sol';
import '../libs/ownership/MultiAdministrable.sol';
/**
* @title MultiAdminRegistry
* @dev Multi-admin registry that allows admins to invoke functions of the backing registry by utilizing the
* contract's registry permissions. Also allows this contract to be cloned with a deterministic address.
* During cloning, new admins will be set and the clone's registry will be set to match this contract's registry.
*/
contract MultiAdminRegistry is MultiAdministrable, CloneableDeterministic {
uint256 constant ELECTION_DURATION_DAYS = 15;
address public creator;
address public registry;
constructor()
public {
// Setting the creator on initial deploy.
// Clones don't invoke the constructor, so we check for the zero address within `init`.
// Cloning invokes `init` immediately after clone creation, so we're never left in a vulnerable state.
creator = msg.sender;
}
/**
* Initializes the contract with the given registry and admin accounts.
* This function should only be invoked from 'clone'.
* @param registryAddress The address of the registry to proxy calls to
* @param adminAddresses The admin address for this contract
*/
function init(address registryAddress, address[] calldata adminAddresses)
external {
require(msg.sender == creator || creator == address(0), "Invocation requires creator");
// Init with admins and threshold of 50% + 1
super.init(adminAddresses, adminAddresses.length / 2 + 1, ELECTION_DURATION_DAYS);
registry = registryAddress;
}
/**
* Sets the registry that this should proxy calls to
* @param r Address of the backing registry
*/
function setRegistry(address r)
onlyAdmins
external {
require(r != address(0), "Valid address required");
registry = r;
}
/**
* Proxy calls to the backing registry
* @dev Passes calls to the backing registry using this contracts address as the sender, allowing admins
* to invoke functions of the registry by piggy-backing off of this contract's permissions.
* View functions will also be rejected by non-admins, but can be invoked against the 'registry'
* address directly.
*/
function ()
onlyAdmins
external {
bytes memory cd = msg.data;
assembly {
let success := call(sub(gas, 1000), sload(registry_slot), 0, add(cd, 0x20), calldatasize, 0, 0)
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize)
if iszero(success) { revert(ptr, returndatasize) }
return(ptr, returndatasize)
}
}
/**
* Clones this registry, setting the registry to this contract's registry and the admins to this contract's admins
* @param salt The salt used to generate the clones address
* @return address The clone's address
*/
function clone(uint256 salt)
public
payable
returns(address payable) {
// Get the current admins
address[] memory a = new address[](uint256(admins.count));
for (int256 i = 0; i < admins.count; i++) {
a[uint256(i)] = admins.at(i);
}
return clone(salt, a);
}
/**
* Clones this registry, setting the registry to this contract's registry and the admins to the provided addresses
* @param salt The salt used to generate the clones address
* @param addresses The admin addresses to use for the clone
* @return address The clone's address
*/
function clone(uint256 salt, address[] memory addresses)
public
payable
onlyAdmins
returns(address payable) {
address payable cloned = super.clone(salt);
(MultiAdminRegistry(cloned)).init(registry, addresses);
return cloned;
}
}
|
Sets the registry that this should proxy calls to r Address of the backing registry/
|
function setRegistry(address r)
onlyAdmins
external {
require(r != address(0), "Valid address required");
registry = r;
}
| 938,848 |
pragma solidity ^0.4.23;
contract Dice2Win {
/// Constants
// Chance to win jackpot - currently 0.1%
uint256 constant JACKPOT_MODULO = 1000;
// Each bet is deducted 2% amount - 1% is house edge, 1% goes to jackpot fund.
uint256 constant HOUSE_EDGE_PERCENT = 2;
uint256 constant JACKPOT_FEE_PERCENT = 50;
// Minimum supported bet is 0.02 ETH, made possible by optimizing gas costs
// compared to our competitors.
uint256 constant MIN_BET = 0.02 ether;
// Only bets higher that 0.1 ETH have a chance to win jackpot.
uint256 constant MIN_JACKPOT_BET = 0.1 ether;
// Random number generation is provided by the hashes of future blocks.
// Two blocks is a good compromise between responsive gameplay and safety from miner attacks.
uint256 constant BLOCK_DELAY = 2;
// Bets made more than 100 blocks ago are considered failed - this has to do
// with EVM limitations on block hashes that are queryable. Settlement failure
// is most probably due to croupier bot failure, if you ever end in this situation
// ask dice2.win support for a refund!
uint256 constant BET_EXPIRATION_BLOCKS = 100;
/// Contract storage.
// Changing ownership of the contract safely
address public owner;
address public nextOwner;
// Max bet limits for coin toss/single dice and double dice respectively.
// Setting these values to zero effectively disables the respective games.
uint256 public maxBetCoinDice;
uint256 public maxBetDoubleDice;
// Current jackpot size.
uint128 public jackpotSize;
// Amount locked in ongoing bets - this is to be sure that we do not commit to bets
// that we cannot fulfill in case of win.
uint128 public lockedInBets;
/// Enum representing games
enum GameId {
CoinFlip,
SingleDice,
DoubleDice,
MaxGameId
}
uint256 constant MAX_BLOCK_NUMBER = 2 ** 56;
uint256 constant MAX_BET_MASK = 2 ** 64;
uint256 constant MAX_AMOUNT = 2 ** 128;
// Struct is tightly packed into a single 256-bit by Solidity compiler.
// This is made to reduce gas costs of placing & settlement transactions.
struct ActiveBet {
// A game that was played.
GameId gameId;
// Block number in which bet transaction was mined.
uint56 placeBlockNumber;
// A binary mask with 1 for each option.
// For example, if you play dice, the mask ranges from 000001 in binary (betting on one)
// to 111111 in binary (betting on all dice outcomes at once).
uint64 mask;
// Bet amount in wei.
uint128 amount;
}
mapping (address => ActiveBet) activeBets;
// Events that are issued to make statistic recovery easier.
event FailedPayment(address indexed _beneficiary, uint256 amount);
event Payment(address indexed _beneficiary, uint256 amount);
event JackpotPayment(address indexed _beneficiary, uint256 amount);
/// Contract governance.
constructor () public {
owner = msg.sender;
// all fields are automatically initialized to zero, which is just what's needed.
}
modifier onlyOwner {
require (msg.sender == owner);
_;
}
// This is pretty standard ownership change routine.
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() public onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () public payable {
}
// Helper routines to alter the respective max bet limits.
function changeMaxBetCoinDice(uint256 newMaxBetCoinDice) public onlyOwner {
maxBetCoinDice = newMaxBetCoinDice;
}
function changeMaxBetDoubleDice(uint256 newMaxBetDoubleDice) public onlyOwner {
maxBetDoubleDice = newMaxBetDoubleDice;
}
// Ability to top up jackpot faster than it's natural growth by house fees.
function increaseJackpot(uint256 increaseAmount) public onlyOwner {
require (increaseAmount <= address(this).balance);
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance);
jackpotSize += uint128(increaseAmount);
}
// Funds withdrawal to cover costs of dice2.win operation.
function withdrawFunds(address beneficiary, uint256 withdrawAmount) public onlyOwner {
require (withdrawAmount <= address(this).balance);
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
/// Betting logic
// Bet transaction - issued by player. Contains the desired game id and betting options
// mask. Wager is the value in ether attached to the transaction.
function placeBet(GameId gameId, uint256 betMask) public payable {
// Check that there is no ongoing bet already - we support one game at a time
// from single address.
ActiveBet storage bet = activeBets[msg.sender];
require (bet.amount == 0);
// Check that the values passed fit into respective limits.
require (gameId < GameId.MaxGameId);
require (msg.value >= MIN_BET && msg.value <= getMaxBet(gameId));
require (betMask < MAX_BET_MASK);
// Determine roll parameters.
uint256 rollModulo = getRollModulo(gameId);
uint256 rollUnder = getRollUnder(rollModulo, betMask);
// Check whether contract has enough funds to process this bet.
uint256 reservedAmount = getDiceWinAmount(msg.value, rollModulo, rollUnder);
uint256 jackpotFee = getJackpotFee(msg.value);
require (jackpotSize + lockedInBets + reservedAmount + jackpotFee <= address(this).balance);
// Update reserved amounts.
lockedInBets += uint128(reservedAmount);
jackpotSize += uint128(jackpotFee);
// Store the bet parameters on blockchain.
bet.gameId = gameId;
bet.placeBlockNumber = uint56(block.number);
bet.mask = uint64(betMask);
bet.amount = uint128(msg.value);
}
// Settlement transaction - can be issued by anyone, but is designed to be handled by the
// dice2.win croupier bot. However nothing prevents you from issuing it yourself, or anyone
// issuing the settlement transaction on your behalf - that does not affect the bet outcome and
// is in fact encouraged in the case the croupier bot malfunctions.
function settleBet(address gambler) public {
// Check that there is already a bet for this gambler.
ActiveBet storage bet = activeBets[gambler];
require (bet.amount != 0);
// Check that the bet is neither too early nor too late.
require (block.number > bet.placeBlockNumber + BLOCK_DELAY);
require (block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS);
// The RNG - use hash of the block that is unknown at the time of placing the bet,
// SHA3 it with gambler address. The latter step is required to make the outcomes of
// different settlement transactions mined into the same block different.
bytes32 entropy = keccak256(gambler, blockhash(bet.placeBlockNumber + BLOCK_DELAY));
uint256 diceWin = 0;
uint256 jackpotWin = 0;
// Determine roll parameters, do a roll by taking a modulo of entropy.
uint256 rollModulo = getRollModulo(bet.gameId);
uint256 dice = uint256(entropy) % rollModulo;
uint256 rollUnder = getRollUnder(rollModulo, bet.mask);
uint256 diceWinAmount = getDiceWinAmount(bet.amount, rollModulo, rollUnder);
// Check the roll result against the bet bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (bet.amount >= MIN_JACKPOT_BET) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
uint256 jackpotRng = (uint256(entropy) / rollModulo) % JACKPOT_MODULO;
// Bingo!
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
// Remove the processed bet from blockchain storage.
delete activeBets[gambler];
// Tally up the win.
uint256 totalWin = diceWin + jackpotWin;
if (totalWin == 0) {
totalWin = 1 wei;
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
// Send the funds to gambler.
sendFunds(gambler, totalWin, diceWin);
}
// Refund transaction - return the bet amount of a roll that was not processed
// in due timeframe (100 Ethereum blocks). Processing such bets is not possible,
// because EVM does not have access to the hashes further than 256 blocks ago.
//
// Like settlement, this transaction may be issued by anyone, but if you ever
// find yourself in situation like this, just contact the dice2.win support!
function refundBet(address gambler) public {
// Check that there is already a bet for this gambler.
ActiveBet storage bet = activeBets[gambler];
require (bet.amount != 0);
// The bet should be indeed late.
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS);
// Determine roll parameters to calculate correct amount of funds locked.
uint256 rollModulo = getRollModulo(bet.gameId);
uint256 rollUnder = getRollUnder(rollModulo, bet.mask);
lockedInBets -= uint128(getDiceWinAmount(bet.amount, rollModulo, rollUnder));
// Delete the bet from the blockchain.
uint256 refundAmount = bet.amount;
delete activeBets[gambler];
// Refund the bet.
sendFunds(gambler, refundAmount, refundAmount);
}
/// Helper routines.
// Number of bet options for specific game.
function getRollModulo(GameId gameId) pure private returns (uint256) {
if (gameId == GameId.CoinFlip) {
// Heads/tails
return 2;
} else if (gameId == GameId.SingleDice) {
// One through six.
return 6;
} else if (gameId == GameId.DoubleDice) {
// 6*6=36 possible outcomes.
return 36;
}
}
// Max bet amount for a specific game.
function getMaxBet(GameId gameId) view private returns (uint256) {
if (gameId == GameId.CoinFlip) {
return maxBetCoinDice;
} else if (gameId == GameId.SingleDice) {
return maxBetCoinDice;
} else if (gameId == GameId.DoubleDice) {
return maxBetDoubleDice;
}
}
// Count 1 bits in the bet bit mask to find the total number of bet options
function getRollUnder(uint256 rollModulo, uint256 betMask) pure private returns (uint256) {
uint256 rollUnder = 0;
uint256 singleBitMask = 1;
for (uint256 shift = 0; shift < rollModulo; shift++) {
if (betMask & singleBitMask != 0) {
rollUnder++;
}
singleBitMask *= 2;
}
return rollUnder;
}
// Get the expected win amount after house edge is subtracted.
function getDiceWinAmount(uint256 amount, uint256 rollModulo, uint256 rollUnder) pure private
returns (uint256) {
require (0 < rollUnder && rollUnder <= rollModulo);
return amount * rollModulo / rollUnder * (100 - HOUSE_EDGE_PERCENT) / 100;
}
// Get the portion of bet amount that is to be accumulated in the jackpot.
function getJackpotFee(uint256 amount) pure private returns (uint256) {
return amount * HOUSE_EDGE_PERCENT / 100 * JACKPOT_FEE_PERCENT / 100;
}
// Helper routine to process the payment.
function sendFunds(address beneficiary, uint256 amount, uint256 successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
}
|
Settlement transaction - can be issued by anyone, but is designed to be handled by the dice2.win croupier bot. However nothing prevents you from issuing it yourself, or anyone issuing the settlement transaction on your behalf - that does not affect the bet outcome and is in fact encouraged in the case the croupier bot malfunctions. Check that there is already a bet for this gambler. Check that the bet is neither too early nor too late. The RNG - use hash of the block that is unknown at the time of placing the bet, SHA3 it with gambler address. The latter step is required to make the outcomes of different settlement transactions mined into the same block different. Determine roll parameters, do a roll by taking a modulo of entropy. Check the roll result against the bet bit mask. Roll for a jackpot (if eligible). The second modulo, statistically independent from the "main" dice roll. Effectively you are playing two games at once! Bingo!
|
function settleBet(address gambler) public {
ActiveBet storage bet = activeBets[gambler];
require (bet.amount != 0);
require (block.number > bet.placeBlockNumber + BLOCK_DELAY);
require (block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS);
bytes32 entropy = keccak256(gambler, blockhash(bet.placeBlockNumber + BLOCK_DELAY));
uint256 diceWin = 0;
uint256 jackpotWin = 0;
uint256 rollModulo = getRollModulo(bet.gameId);
uint256 dice = uint256(entropy) % rollModulo;
uint256 rollUnder = getRollUnder(rollModulo, bet.mask);
uint256 diceWinAmount = getDiceWinAmount(bet.amount, rollModulo, rollUnder);
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
if (bet.amount >= MIN_JACKPOT_BET) {
uint256 jackpotRng = (uint256(entropy) / rollModulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (totalWin == 0) {
totalWin = 1 wei;
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
}
| 2,568,781 |
// File: @openzeppelin/contracts/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 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: @openzeppelin/contracts/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/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() {
_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);
}
}
// File: @openzeppelin/contracts/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/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/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/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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 ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @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 ERC721Enumerable is ERC721, IERC721Enumerable {
// 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(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.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 < ERC721Enumerable.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 = ERC721.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 = ERC721.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();
}
}
// File: @openzeppelin/contracts/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/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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
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);
}
// File: contracts/skvllpvnkz.sol
pragma solidity ^0.8.0;
contract Skvllpvnkz is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
/* Events */
event SkvllpvnkzFreeMintStarted();
event SkvllpvnkzFreeMintPaused();
event SkvllpvnkzPublicSaleStarted();
event SkvllpvnkzPublicSalePaused();
event SkvllpvnkzPresaleStarted();
event SkvllpvnkzPresalePaused();
/* Supply Pools
** These are the total supply amounts for each pool.
** We have 3 supply pools:
** 1. Reserved giveaway pool for future giveaways
** 2. Reserved early free mint pool for previous collection owners
** 3. Public presale and open sale pool available to everyone */
uint256 private _maxSupply = 10000;
uint256 private _rsrvdGiveawaySupply = 100;
uint256 private _rsrvdEarlySupply = 356;
uint256 private _unrsrvdSupply = _maxSupply - _rsrvdGiveawaySupply - _rsrvdEarlySupply;
/* Token IDs
** Token ID ranges are reserved for the 3 different pools.
** _rsrvdGiveawayTID -> _rsrvdEarlyTID -> _tokenId */
uint256 private _rsrvdGiveawayTID = 0; // This is the starting ID
uint256 private _rsrvdEarlyTID = _rsrvdGiveawaySupply;
uint256 private _tokenId = _rsrvdGiveawaySupply + _rsrvdEarlySupply;
// The base URI for the token
string _baseTokenURI;
// The maximum mint batch size per transaction for the public sale
uint256 private _maxBatch = 10;
// The maximum mint batch size per transaction for the presale
uint256 private _maxBatchPresale = 2;
// The price per mint
uint256 private _price = 0.05 ether;
// Flag to start / pause public sale
bool public _publicSale = false;
// Flag to start / pause presale
bool public _presale = false;
// Flag to start / pause presale
bool public _ownerSale = false;
bool private _provenanceSet = false;
string private _contractURI = "http://api.skvllpvnkz.io/contract";
uint256 private _walletLimit = 200;
string public provenance = "";
/* Whitelists
** We have 2 separte whitelists:
** 2. Presale whitelist for Outcasts */
mapping(address => uint256) private _presaleList;
mapping(address => uint256) private _freeList;
// Withdraw addresses
address t1 = 0xAD5e57aCB70635671d6FEa67b08FB56f3eff596e;
address t2 = 0xE3f33298381C7694cf5e999B36fD513a0Ddec8ba;
address t3 = 0x58723Ef34C6F1197c30B35fC763365508d24b448;
address t4 = 0x46F231aD0279dA2d249D690Ab1e92F1B1f1F0158;
address t5 = 0xcdA2E4b965eCa883415107b624e971c4Cefc4D8C;
modifier notContract {
require( !_isContract( msg.sender ), "Cannot call this from a contract " );
_;
}
constructor() ERC721("Skvllpvnkz Hideout", "SKVLLZ") {}
/* Presale Mint
** Presale minting is available before the public sale to users
** on the presale whitelist. Wallets on the whitelist will be allowed
** to mint a maximum of 2 avatars */
function presaleRecruit(uint256 num) external payable nonReentrant notContract{
require( _presale, "Presale paused" );
require( _presaleList[msg.sender] > 0, "Not on the whitelist");
require( num <= _maxBatchPresale, "Exceeds the maximum amount" );
require( _presaleList[msg.sender] >= num, 'Purchase exceeds max allowed');
require( num <= remainingSupply(), "Exceeds reserved supply" );
require( msg.value >= _price * num, "Ether sent is not correct" );
_presaleList[msg.sender] -= num;
for(uint256 i; i < num; i++){
_tokenId ++;
_safeMint( msg.sender, _tokenId );
}
}
/* Standard Mint
** This is the standard mint function allowing a user to mint a
** maximum of 10 avatars. It mints the tokens from a pool of IDs
** starting after the initial reserved token pools */
function recruit(uint256 num) external payable nonReentrant notContract {
require( !_isContract( msg.sender ), "Cannot call this from a contract " );
require( _publicSale, "Sale paused" );
require( num <= _maxBatch, "Max 10 per TX" );
require( num <= remainingSupply(), "Exceeds maximum supply" );
require( balanceOf(msg.sender) + num <= _walletLimit, "Exceeds wallet limit");
require( msg.value >= _price * num, "Incorrect Ether sent" );
for( uint256 i; i < num; i++ ){
if (_tokenId <= _maxSupply) {
_tokenId ++;
_safeMint( msg.sender, _tokenId );
}
}
}
/* Giveaway Mint
** This is the standard mint function allowing a user to mint a
** maximum of 20 avatars. It mints the tokens from a pool of IDs
** starting after the initial reserved token pools */
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _amount <= remainingGiveaways(), "Exceeds reserved supply" );
for(uint256 i; i < _amount; i++){
_rsrvdGiveawayTID ++;
_safeMint( _to, _rsrvdGiveawayTID);
}
}
function freeRecruit() external payable nonReentrant notContract {
require( _ownerSale, "Free mint is not on" );
require( _freeList[msg.sender] > 0, "Not on the whitelist");
require( _freeList[msg.sender] <= remainingEarlySupply(), "Exceeds reserved supply" );
uint256 mintCnt = _freeList[msg.sender];
_freeList[msg.sender] = 0;
for( uint256 i; i < mintCnt; i++ ){
_rsrvdEarlyTID ++;
_safeMint( msg.sender, _rsrvdEarlyTID );
}
}
function _isContract(address _addr) internal view returns (bool) {
uint32 _size;
assembly {
_size:= extcodesize(_addr)
}
return (_size > 0);
}
/* Remove wallet from the free mint whitelist */
function removeFromFreeList(address _address) external onlyOwner {
_freeList[_address] = 0;
}
/* Add wallet to the presale whitelist */
function addToFreeList(address[] calldata addresses, uint256[] calldata count) external onlyOwner{
for (uint256 i = 0; i < addresses.length; i++) {
_freeList[addresses[i]] = count[i];
}
}
/* Add wallet to the presale whitelist */
function addToPresaleList(address[] calldata addresses) external onlyOwner{
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add a null address");
_presaleList[addresses[i]] = _maxBatchPresale;
}
}
/* Remove wallet from the presale whitelist */
function removeFromPresaleList(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't remove a null address");
_presaleList[addresses[i]] = 0;
}
}
function onPresaleList(address addr) external view returns (uint256) {
return _presaleList[addr];
}
function onFreeList(address addr) external view returns (uint256) {
return _freeList[addr];
}
function walletOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function publicSale(bool val) external onlyOwner {
_publicSale = val;
if (val) {
_presale = false;
emit SkvllpvnkzPublicSaleStarted();
emit SkvllpvnkzPresalePaused();
} else {
emit SkvllpvnkzPublicSalePaused();
}
}
function freeMint(bool val) external onlyOwner {
_ownerSale = val;
if (val) {
emit SkvllpvnkzFreeMintStarted();
} else {
emit SkvllpvnkzFreeMintPaused();
}
}
function presale(bool val) external onlyOwner {
require(!_publicSale, "Can't have a presale during the public sale");
_presale = val;
if (val) {
emit SkvllpvnkzPresaleStarted();
} else {
emit SkvllpvnkzPresalePaused();
}
}
function setPrice(uint256 _newPrice) external onlyOwner() {
_price = _newPrice;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setMaxBatch(uint256 maxBatch) external onlyOwner {
_maxBatch = maxBatch;
}
function getMaxBatch() external view returns (uint256) {
return _maxBatch;
}
function getPrice() external view returns (uint256){
return _price;
}
function remainingTotalSupply() external view returns (uint256){
return _maxSupply - totalSupply();
}
function remainingSupply() public view returns (uint256) {
return _unrsrvdSupply + _rsrvdEarlySupply + _rsrvdGiveawaySupply - _tokenId;
}
function remainingGiveaways() public view returns (uint256){
return _rsrvdGiveawaySupply - _rsrvdGiveawayTID;
}
function remainingEarlySupply() public view returns (uint256){
return _rsrvdEarlySupply + _rsrvdGiveawaySupply - _rsrvdEarlyTID;
}
function maxSupply() external view returns (uint256){
return _maxSupply;
}
function withdraw(uint256 amount) external payable onlyOwner {
require(payable(msg.sender).send(amount));
}
function withdrawAll() external payable onlyOwner {
uint256 _each = address(this).balance / 100;
require(payable(t1).send( _each * 31 )); // TM1
require(payable(t2).send( _each * 21 )); // TM2
require(payable(t3).send( _each * 21 )); // TM3
require(payable(t4).send( _each * 21 )); // TM4
require(payable(t5).send( _each * 6 )); // Comm
}
function setWalletLimit(uint256 limit) external onlyOwner {
_walletLimit = limit;
}
function setContractURI(string memory uri) external onlyOwner {
_contractURI = uri;
}
function contractURI() external view returns (string memory) {
return _contractURI;
}
function setProvenance(string memory _provenance) external onlyOwner {
require(!_provenanceSet, "Provenance has been set already");
provenance = _provenance;
_provenanceSet = true;
}
}
|
See {IERC165-supportsInterface}./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
| 353,601 |
./full_match/1/0xA309c1E54d91b9f45845c4899A7e35999540406B/sources/contracts/staking/StakingPool.sol
|
Blacklist or unblacklist an address. _user Address of user _status Status (true or false)
|
function setBlackListed(address _user, bool _status) external onlyOwner {
isBlackListed[_user] = _status;
emit SetBlackListed(_user, _status);
}
| 17,053,117 |
./partial_match/1/0x887fAdFC958C44cc0bAb0E211ec8bfba67Cee03b/sources/contracts/Halo/HaloNFTV2.sol
|
function to get the minted number of the address./
|
function mintedNumber(address addr) external override view returns(uint256) {
addr;
return _numberMinted;
}
| 4,205,728 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
library CoreLibrary {
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address payable);
function getLendingPoolDataProvider() external view returns (address);
function getLendingPoolParametersProvider() external view returns (address);
function getPriceOracle() external view returns (address);
}
interface ILendingPoolCore {
function getReserves() external view returns (address[] memory);
function getReserveTotalLiquidity(address _reserve) external view returns (uint256);
function getReserveAvailableLiquidity(address _reserve) external view returns (uint256);
function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve) external view returns (uint256);
function getReserveCurrentAverageStableBorrowRate(address _reserve)
external
view
returns (uint256);
function getReserveUtilizationRate(address _reserve) external view returns (uint256);
function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256);
function getReserveVariableBorrowsCumulativeIndex(address _reserve)
external
view
returns (uint256);
function getReserveATokenAddress(address _reserve) external view returns (address);
function getReserveLastUpdate(address _reserve) external view returns (uint40);
// configuration
function getReserveConfiguration(address _reserve)
external
view
returns (
uint256,
uint256,
uint256,
bool
);
function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool);
function isReserveBorrowingEnabled(address _reserve) external view returns (bool);
function getReserveIsActive(address _reserve) external view returns (bool);
function getReserveIsFreezed(address _reserve) external view returns (bool);
function getReserveLiquidationBonus(address _reserve) external view returns (uint256);
// user related
function getUserOriginationFee(address _reserve, address _user) external view returns (uint256);
function getUserBorrowBalances(address _reserve, address _user)
external
view
returns (
uint256,
uint256,
uint256
);
function getUserCurrentBorrowRateMode(address _reserve, address _user)
external
view
returns (CoreLibrary.InterestRateMode);
function getUserCurrentStableBorrowRate(address _reserve, address _user)
external
view
returns (uint256);
function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)
external
view
returns (uint256);
function getUserLastUpdate(address _reserve, address _user) external view returns (uint40);
function isUserUseReserveAsCollateralEnabled(address _reserve, address _user)
external
view
returns (bool);
}
interface IAToken {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function underlyingAssetAddress() external view returns (address);
function principalBalanceOf(address _user) external view returns (uint256);
function getUserIndex(address _user) external view returns (uint256);
function getInterestRedirectionAddress(address _user) external view returns (address);
function getRedirectedBalance(address _user) external view returns (uint256);
}
interface IPoolDataProvider {
struct ReserveData {
address underlyingAsset;
string name;
string symbol;
uint8 decimals;
bool isActive;
bool isFreezed;
bool usageAsCollateralEnabled;
bool borrowingEnabled;
bool stableBorrowRateEnabled;
uint256 baseLTVasCollateral;
uint256 averageStableBorrowRate;
uint256 liquidityIndex;
uint256 reserveLiquidationThreshold;
uint256 reserveLiquidationBonus;
uint256 variableBorrowIndex;
uint256 variableBorrowRate;
uint256 availableLiquidity;
uint256 stableBorrowRate;
uint256 liquidityRate;
uint256 totalBorrowsStable;
uint256 totalBorrowsVariable;
uint256 totalLiquidity;
uint256 utilizationRate;
uint40 lastUpdateTimestamp;
uint256 priceInEth;
address aTokenAddress;
}
struct UserReserveData {
address underlyingAsset;
uint256 principalATokenBalance;
uint256 userBalanceIndex;
uint256 redirectedBalance;
address interestRedirectionAddress;
bool usageAsCollateralEnabledOnUser;
uint256 borrowRate;
CoreLibrary.InterestRateMode borrowRateMode;
uint256 originationFee;
uint256 principalBorrows;
uint256 variableBorrowIndex;
uint256 lastUpdateTimestamp;
}
struct ATokenSupplyData {
string name;
string symbol;
uint8 decimals;
uint256 totalSupply;
address aTokenAddress;
}
function getReservesData(ILendingPoolAddressesProvider provider)
external
view
returns (ReserveData[] memory, uint256);
function getUserReservesData(ILendingPoolAddressesProvider provider, address user)
external
view
returns (UserReserveData[] memory);
function getAllATokenSupply(ILendingPoolAddressesProvider provider)
external
view
returns (ATokenSupplyData[] memory);
function getATokenSupply(address[] calldata aTokens)
external
view
returns (ATokenSupplyData[] memory);
}
interface IChainlinkProxyPriceProvider {
function getAssetPrice(address _asset) external view returns (uint256);
}
contract PoolDataProvider is IPoolDataProvider {
constructor() public {}
address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96;
function getReservesData(ILendingPoolAddressesProvider provider)
external
override
view
returns (ReserveData[] memory, uint256)
{
ILendingPoolCore core = ILendingPoolCore(provider.getLendingPoolCore());
IChainlinkProxyPriceProvider oracle = IChainlinkProxyPriceProvider(provider.getPriceOracle());
address[] memory reserves = core.getReserves();
ReserveData[] memory reservesData = new ReserveData[](reserves.length);
address reserve;
for (uint256 i = 0; i < reserves.length; i++) {
reserve = reserves[i];
ReserveData memory reserveData = reservesData[i];
// base asset info
reserveData.aTokenAddress = core.getReserveATokenAddress(reserve);
IAToken assetDetails = IAToken(reserveData.aTokenAddress);
reserveData.decimals = assetDetails.decimals();
// we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed
reserveData.symbol = assetDetails.symbol();
reserveData.name = '';
// reserve configuration
reserveData.underlyingAsset = reserve;
reserveData.isActive = core.getReserveIsActive(reserve);
reserveData.isFreezed = core.getReserveIsFreezed(reserve);
(
,
reserveData.baseLTVasCollateral,
reserveData.reserveLiquidationThreshold,
reserveData.usageAsCollateralEnabled
) = core.getReserveConfiguration(reserve);
reserveData.stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(reserve);
reserveData.borrowingEnabled = core.isReserveBorrowingEnabled(reserve);
reserveData.reserveLiquidationBonus = core.getReserveLiquidationBonus(reserve);
reserveData.priceInEth = oracle.getAssetPrice(reserve);
// reserve current state
reserveData.totalLiquidity = core.getReserveTotalLiquidity(reserve);
reserveData.availableLiquidity = core.getReserveAvailableLiquidity(reserve);
reserveData.totalBorrowsStable = core.getReserveTotalBorrowsStable(reserve);
reserveData.totalBorrowsVariable = core.getReserveTotalBorrowsVariable(reserve);
reserveData.liquidityRate = core.getReserveCurrentLiquidityRate(reserve);
reserveData.variableBorrowRate = core.getReserveCurrentVariableBorrowRate(reserve);
reserveData.stableBorrowRate = core.getReserveCurrentStableBorrowRate(reserve);
reserveData.averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(reserve);
reserveData.utilizationRate = core.getReserveUtilizationRate(reserve);
reserveData.liquidityIndex = core.getReserveLiquidityCumulativeIndex(reserve);
reserveData.variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(reserve);
reserveData.lastUpdateTimestamp = core.getReserveLastUpdate(reserve);
}
return (reservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS));
}
function getUserReservesData(ILendingPoolAddressesProvider provider, address user)
external
override
view
returns (UserReserveData[] memory)
{
ILendingPoolCore core = ILendingPoolCore(provider.getLendingPoolCore());
address[] memory reserves = core.getReserves();
UserReserveData[] memory userReservesData = new UserReserveData[](reserves.length);
address reserve;
for (uint256 i = 0; i < reserves.length; i++) {
reserve = reserves[i];
IAToken aToken = IAToken(core.getReserveATokenAddress(reserve));
UserReserveData memory userReserveData = userReservesData[i];
userReserveData.underlyingAsset = reserve;
userReserveData.principalATokenBalance = aToken.principalBalanceOf(user);
(userReserveData.principalBorrows, , ) = core.getUserBorrowBalances(reserve, user);
userReserveData.borrowRateMode = core.getUserCurrentBorrowRateMode(reserve, user);
if (userReserveData.borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
userReserveData.borrowRate = core.getUserCurrentStableBorrowRate(reserve, user);
}
userReserveData.originationFee = core.getUserOriginationFee(reserve, user);
userReserveData.variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(
reserve,
user
);
userReserveData.userBalanceIndex = aToken.getUserIndex(user);
userReserveData.redirectedBalance = aToken.getRedirectedBalance(user);
userReserveData.interestRedirectionAddress = aToken.getInterestRedirectionAddress(user);
userReserveData.lastUpdateTimestamp = core.getUserLastUpdate(reserve, user);
userReserveData.usageAsCollateralEnabledOnUser = core.isUserUseReserveAsCollateralEnabled(
reserve,
user
);
}
return userReservesData;
}
/**
Gets the total supply of all aTokens for a specific market
@param provider The LendingPoolAddressProvider contract, different for each market.
*/
function getAllATokenSupply(ILendingPoolAddressesProvider provider)
external
override
view
returns (ATokenSupplyData[] memory)
{
ILendingPoolCore core = ILendingPoolCore(provider.getLendingPoolCore());
address[] memory allReserves = core.getReserves();
address[] memory allATokens = new address[](allReserves.length);
for (uint256 i = 0; i < allReserves.length; i++) {
allATokens[i] = core.getReserveATokenAddress(allReserves[i]);
}
return getATokenSupply(allATokens);
}
/**
Gets the total supply of associated reserve aTokens
@param aTokens An array of aTokens addresses
*/
function getATokenSupply(address[] memory aTokens)
public
override
view
returns (ATokenSupplyData[] memory)
{
ATokenSupplyData[] memory totalSuppliesData = new ATokenSupplyData[](aTokens.length);
address aTokenAddress;
for (uint256 i = 0; i < aTokens.length; i++) {
aTokenAddress = aTokens[i];
IAToken aToken = IAToken(aTokenAddress);
totalSuppliesData[i] = ATokenSupplyData({
name: aToken.name(),
symbol: aToken.symbol(),
decimals: aToken.decimals(),
totalSupply: aToken.totalSupply(),
aTokenAddress: aTokenAddress
});
}
return totalSuppliesData;
}
}
|
configuration user related
|
interface ILendingPoolCore {
function getReserves() external view returns (address[] memory);
function getReserveTotalLiquidity(address _reserve) external view returns (uint256);
function getReserveAvailableLiquidity(address _reserve) external view returns (uint256);
function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve) external view returns (uint256);
function getReserveCurrentAverageStableBorrowRate(address _reserve)
external
view
returns (uint256);
function getReserveUtilizationRate(address _reserve) external view returns (uint256);
function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256);
function getReserveVariableBorrowsCumulativeIndex(address _reserve)
external
view
returns (uint256);
function getReserveATokenAddress(address _reserve) external view returns (address);
function getReserveLastUpdate(address _reserve) external view returns (uint40);
function getReserveConfiguration(address _reserve)
external
view
returns (
uint256,
uint256,
uint256,
bool
);
function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool);
function isReserveBorrowingEnabled(address _reserve) external view returns (bool);
function getReserveIsActive(address _reserve) external view returns (bool);
function getReserveIsFreezed(address _reserve) external view returns (bool);
function getReserveLiquidationBonus(address _reserve) external view returns (uint256);
function getUserOriginationFee(address _reserve, address _user) external view returns (uint256);
function getUserBorrowBalances(address _reserve, address _user)
external
view
returns (
uint256,
uint256,
uint256
);
function getUserCurrentBorrowRateMode(address _reserve, address _user)
external
view
returns (CoreLibrary.InterestRateMode);
function getUserCurrentStableBorrowRate(address _reserve, address _user)
external
view
returns (uint256);
function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)
external
view
returns (uint256);
function getUserLastUpdate(address _reserve, address _user) external view returns (uint40);
function isUserUseReserveAsCollateralEnabled(address _reserve, address _user)
external
view
returns (bool);
}
| 15,054,574 |
pragma solidity ^0.5.0;
import "./EternalStorage.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./IIterableEternalStorage.sol";
contract IterableEternalStorage is EternalStorage, IIterableEternalStorage {
using SafeMath for uint256;
bytes32 private constant SIZE_POSTFIX = "listSize";
bytes32 private constant VALUES_POSTFIX = "listValues";
bytes32 private constant INDEX_POSTFIX = "listIndex";
bytes32 private constant EXISTS_POSTFIX = "listExists";
bytes32 private constant UINT8_ID = "uint8";
bytes32 private constant UINT16_ID = "uint16";
bytes32 private constant UINT32_ID = "uint32";
bytes32 private constant UINT64_ID = "uint64";
bytes32 private constant UINT128_ID = "uint128";
bytes32 private constant UINT256_ID = "uint256";
bytes32 private constant INT8_ID = "int8";
bytes32 private constant INT16_ID = "int16";
bytes32 private constant INT32_ID = "int32";
bytes32 private constant INT64_ID = "int64";
bytes32 private constant INT128_ID = "int128";
bytes32 private constant INT256_ID = "int256";
bytes32 private constant ADDRESS_ID = "address";
bytes32 private constant BYTES8_ID = "bytes8";
bytes32 private constant BYTES16_ID = "bytes16";
bytes32 private constant BYTES32_ID = "bytes32";
bytes32 private constant STRING_ID = "string";
// *** UInt8 ***
function addUInt8Key(bytes32 _listId, uint8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(UINT8_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(UINT8_ID, _listId, valueHash);
setUInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeUInt8Key(bytes32 _listId, uint8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(UINT8_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(UINT8_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(UINT8_ID, _listId, valueHash);
deleteUInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
uint8 lastValueOfList = getUInt8KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setUInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
UINT8_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteUInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getUInt8KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(UINT8_ID, _listId);
}
function getUInt8Keys(bytes32 _listId) public view returns (uint8[] memory) {
return getRangeOfUInt8Keys(_listId, 0, getUInt8KeySize(_listId));
}
function getRangeOfUInt8Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (uint8[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getUInt8KeySize(_listId), _offset, _limit);
uint8[] memory list = new uint8[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getUInt8KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getUInt8KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (uint8) {
return getUInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsUInt8Key(bytes32 _listId, uint8 _value) public view returns (bool) {
return _existsInIterableList(UINT8_ID, _listId, keccak256(abi.encode(_value)));
}
// *** UInt128 ***
function addUInt128Key(bytes32 _listId, uint128 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(UINT128_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(UINT128_ID, _listId, valueHash);
setUInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeUInt128Key(bytes32 _listId, uint128 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(UINT128_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(UINT128_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(UINT128_ID, _listId, valueHash);
deleteUInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
uint128 lastValueOfList = getUInt128KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setUInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
UINT128_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteUInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getUInt128KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(UINT128_ID, _listId);
}
function getUInt128Keys(bytes32 _listId) public view returns (uint128[] memory) {
return getRangeOfUInt128Keys(_listId, 0, getUInt128KeySize(_listId));
}
function getRangeOfUInt128Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (uint128[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getUInt128KeySize(_listId), _offset, _limit);
uint128[] memory list = new uint128[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getUInt128KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getUInt128KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (uint128) {
return getUInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsUInt128Key(bytes32 _listId, uint128 _value) public view returns (bool) {
return _existsInIterableList(UINT128_ID, _listId, keccak256(abi.encode(_value)));
}
// *** UInt256 ***
function addUInt256Key(bytes32 _listId, uint256 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(UINT256_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(UINT256_ID, _listId, valueHash);
setUInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeUInt256Key(bytes32 _listId, uint256 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(UINT256_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(UINT256_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(UINT256_ID, _listId, valueHash);
deleteUInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
uint256 lastValueOfList = getUInt256KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setUInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
UINT256_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteUInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getUInt256KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(UINT256_ID, _listId);
}
function getUInt256Keys(bytes32 _listId) public view returns (uint256[] memory) {
return getRangeOfUInt256Keys(_listId, 0, getUInt256KeySize(_listId));
}
function getRangeOfUInt256Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (uint256[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getUInt256KeySize(_listId), _offset, _limit);
uint256[] memory list = new uint256[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getUInt256KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getUInt256KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (uint256) {
return getUInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsUInt256Key(bytes32 _listId, uint256 _value) public view returns (bool) {
return _existsInIterableList(UINT256_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Int8 ***
function addInt8Key(bytes32 _listId, int8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(INT8_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(INT8_ID, _listId, valueHash);
setInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeInt8Key(bytes32 _listId, int8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(INT8_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(INT8_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(INT8_ID, _listId, valueHash);
deleteInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
int8 lastValueOfList = getInt8KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
INT8_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getInt8KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(INT8_ID, _listId);
}
function getInt8Keys(bytes32 _listId) public view returns (int8[] memory) {
return getRangeOfInt8Keys(_listId, 0, getInt8KeySize(_listId));
}
function getRangeOfInt8Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (int8[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getInt8KeySize(_listId), _offset, _limit);
int8[] memory list = new int8[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getInt8KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getInt8KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (int8) {
return getInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsInt8Key(bytes32 _listId, int8 _value) public view returns (bool) {
return _existsInIterableList(INT8_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Int128 ***
function addInt128Key(bytes32 _listId, int128 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(INT128_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(INT128_ID, _listId, valueHash);
setInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeInt128Key(bytes32 _listId, int128 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(INT128_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(INT128_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(INT128_ID, _listId, valueHash);
deleteInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
int128 lastValueOfList = getInt128KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
INT128_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getInt128KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(INT128_ID, _listId);
}
function getInt128Keys(bytes32 _listId) public view returns (int128[] memory) {
return getRangeOfInt128Keys(_listId, 0, getInt128KeySize(_listId));
}
function getRangeOfInt128Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (int128[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getInt128KeySize(_listId), _offset, _limit);
int128[] memory list = new int128[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getInt128KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getInt128KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (int128) {
return getInt128(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsInt128Key(bytes32 _listId, int128 _value) public view returns (bool) {
return _existsInIterableList(INT128_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Int256 ***
function addInt256Key(bytes32 _listId, int256 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(INT256_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(INT256_ID, _listId, valueHash);
setInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeInt256Key(bytes32 _listId, int256 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(INT256_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(INT256_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(INT256_ID, _listId, valueHash);
deleteInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
int256 lastValueOfList = getInt256KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
INT256_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getInt256KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(INT256_ID, _listId);
}
function getInt256Keys(bytes32 _listId) public view returns (int256[] memory) {
return getRangeOfInt256Keys(_listId, 0, getInt256KeySize(_listId));
}
function getRangeOfInt256Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (int256[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getInt256KeySize(_listId), _offset, _limit);
int256[] memory list = new int256[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getInt256KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getInt256KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (int256) {
return getInt256(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsInt256Key(bytes32 _listId, int256 _value) public view returns (bool) {
return _existsInIterableList(INT256_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Address ***
function addAddressKey(bytes32 _listId, address _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(ADDRESS_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(ADDRESS_ID, _listId, valueHash);
setAddress(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeAddressKey(bytes32 _listId, address _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(ADDRESS_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(ADDRESS_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(ADDRESS_ID, _listId, valueHash);
deleteAddress(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
address lastValueOfList = getAddressKeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setAddress(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
ADDRESS_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteAddress(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getAddressKeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(ADDRESS_ID, _listId);
}
function getAddressKeys(bytes32 _listId) public view returns (address[] memory) {
return getRangeOfAddressKeys(_listId, 0, getAddressKeySize(_listId));
}
function getRangeOfAddressKeys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (address[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getAddressKeySize(_listId), _offset, _limit);
address[] memory list = new address[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getAddressKeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getAddressKeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (address) {
return getAddress(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsAddressKey(bytes32 _listId, address _value) public view returns (bool) {
return _existsInIterableList(ADDRESS_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Bytes8 ***
function addBytes8Key(bytes32 _listId, bytes8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(BYTES8_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(BYTES8_ID, _listId, valueHash);
setBytes8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeBytes8Key(bytes32 _listId, bytes8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(BYTES8_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(BYTES8_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(BYTES8_ID, _listId, valueHash);
deleteBytes8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
bytes8 lastValueOfList = getBytes8KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setBytes8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
BYTES8_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteBytes8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getBytes8KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(BYTES8_ID, _listId);
}
function getBytes8Keys(bytes32 _listId) public view returns (bytes8[] memory) {
return getRangeOfBytes8Keys(_listId, 0, getBytes8KeySize(_listId));
}
function getRangeOfBytes8Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (bytes8[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getBytes8KeySize(_listId), _offset, _limit);
bytes8[] memory list = new bytes8[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getBytes8KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getBytes8KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (bytes8) {
return getBytes8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsBytes8Key(bytes32 _listId, bytes8 _value) public view returns (bool) {
return _existsInIterableList(BYTES8_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Bytes16 ***
function addBytes16Key(bytes32 _listId, bytes16 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(BYTES16_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(BYTES16_ID, _listId, valueHash);
setBytes16(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeBytes16Key(bytes32 _listId, bytes16 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(BYTES16_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(BYTES16_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(BYTES16_ID, _listId, valueHash);
deleteBytes16(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
bytes16 lastValueOfList = getBytes16KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setBytes16(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
BYTES16_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteBytes16(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getBytes16KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(BYTES16_ID, _listId);
}
function getBytes16Keys(bytes32 _listId) public view returns (bytes16[] memory) {
return getRangeOfBytes16Keys(_listId, 0, getBytes16KeySize(_listId));
}
function getRangeOfBytes16Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (bytes16[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getBytes16KeySize(_listId), _offset, _limit);
bytes16[] memory list = new bytes16[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getBytes16KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getBytes16KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (bytes16) {
return getBytes16(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsBytes16Key(bytes32 _listId, bytes16 _value) public view returns (bool) {
return _existsInIterableList(BYTES16_ID, _listId, keccak256(abi.encode(_value)));
}
// *** Bytes32 ***
function addBytes32Key(bytes32 _listId, bytes32 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(BYTES32_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(BYTES32_ID, _listId, valueHash);
setBytes32(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeBytes32Key(bytes32 _listId, bytes32 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(BYTES32_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(BYTES32_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(BYTES32_ID, _listId, valueHash);
deleteBytes32(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
bytes32 lastValueOfList = getBytes32KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setBytes32(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
BYTES32_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteBytes32(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getBytes32KeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(BYTES32_ID, _listId);
}
function getBytes32Keys(bytes32 _listId) public view returns (bytes32[] memory) {
return getRangeOfBytes32Keys(_listId, 0, getBytes32KeySize(_listId));
}
function getRangeOfBytes32Keys(bytes32 _listId, uint256 _offset, uint256 _limit) public view returns (bytes32[] memory) {
uint256 rangeSize = _calculateRangeSizeOfList(getBytes32KeySize(_listId), _offset, _limit);
bytes32[] memory list = new bytes32[](rangeSize);
for (uint256 listIndex = 0; listIndex < rangeSize; listIndex++) {
list[listIndex] = getBytes32KeyByIndex(_listId, listIndex + _offset);
}
return list;
}
function getBytes32KeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (bytes32) {
return getBytes32(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsBytes32Key(bytes32 _listId, bytes32 _value) public view returns (bool) {
return _existsInIterableList(BYTES32_ID, _listId, keccak256(abi.encode(_value)));
}
// *** String ***
function addStringKey(bytes32 _listId, string memory _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(!_existsInIterableList(STRING_ID, _listId, valueHash), "Key exists already in the list");
uint256 index = _createKeyEntry(STRING_ID, _listId, valueHash);
setString(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), _value);
}
function removeStringKey(bytes32 _listId, string memory _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(STRING_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(STRING_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(STRING_ID, _listId, valueHash);
deleteString(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
// replace position of deleted key with the last key in the list, to avoid gaps
if (index != lastKeyIndex) {
string memory lastValueOfList = getStringKeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setString(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
STRING_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
// delete old position at last position
deleteString(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
function getStringKeySize(bytes32 _listId) public view returns (uint256) {
return _getKeySize(STRING_ID, _listId);
}
function getStringKeyByIndex(bytes32 _listId, uint256 _listIndex) public view returns (string memory) {
return getString(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, _listIndex)));
}
function existsStringKey(bytes32 _listId, string memory _value) public view returns (bool) {
return _existsInIterableList(STRING_ID, _listId, keccak256(abi.encode(_value)));
}
function _existsInIterableList(bytes32 _typeId, bytes32 _listId, bytes32 _valueHash) private view returns (bool) {
return getBool(
keccak256(
abi.encodePacked(
_typeId,
_listId,
EXISTS_POSTFIX,
_valueHash
)
)
);
}
function _getKeySize(bytes32 _typeId, bytes32 _listId) private view returns (uint256) {
return getUInt256(keccak256(abi.encodePacked(_typeId, _listId, SIZE_POSTFIX)));
}
function _setIterableListSize(bytes32 _typeId, bytes32 _listId, uint256 _listSize) private {
setUInt256(keccak256(abi.encodePacked(_typeId, _listId, SIZE_POSTFIX)), _listSize);
}
function _calculateRangeSizeOfList(uint256 _listSize, uint256 _offset, uint256 _limit) private pure returns (uint256) {
require(_offset < _listSize, "Offset is out of range");
uint256 rangeSize = _listSize.sub(_offset);
if (rangeSize > _limit) {
rangeSize = _limit;
}
return rangeSize;
}
function _createKeyEntry(bytes32 _typeId, bytes32 _listId, bytes32 _valueHash) private returns (uint256) {
// the new index is equal to the size of the list before adding a new value
uint256 newIndex = _getKeySize(_typeId, _listId);
setUInt256(
keccak256(
abi.encodePacked(
_typeId,
_listId,
INDEX_POSTFIX,
_valueHash
)
),
newIndex
);
setBool(
keccak256(
abi.encodePacked(
_typeId,
_listId,
EXISTS_POSTFIX,
_valueHash
)
),
true
);
// the list size is the latest index plus 1
_setIterableListSize(_typeId, _listId, newIndex + 1);
return newIndex;
}
function _removeKeyEntry(bytes32 _typeId, bytes32 _listId, bytes32 _valueHash) private returns (uint256) {
uint256 index = getUInt256(
keccak256(
abi.encodePacked(
_typeId,
_listId,
INDEX_POSTFIX,
_valueHash
)
)
);
deleteUInt256(
keccak256(
abi.encodePacked(
_typeId,
_listId,
INDEX_POSTFIX,
_valueHash
)
)
);
deleteBool(
keccak256(
abi.encodePacked(
_typeId,
_listId,
EXISTS_POSTFIX,
_valueHash
)
)
);
_setIterableListSize(_typeId, _listId, _getKeySize(_typeId, _listId) - 1);
return index;
}
}
|
replace position of deleted key with the last key in the list, to avoid gaps delete old position at last position
|
function removeInt8Key(bytes32 _listId, int8 _value) public {
bytes32 valueHash = keccak256(abi.encode(_value));
require(_existsInIterableList(INT8_ID, _listId, valueHash), "Key does not exist in the list");
uint256 keySize = _getKeySize(INT8_ID, _listId);
uint256 lastKeyIndex = keySize - 1;
uint256 index = _removeKeyEntry(INT8_ID, _listId, valueHash);
deleteInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)));
if (index != lastKeyIndex) {
int8 lastValueOfList = getInt8KeyByIndex(_listId, lastKeyIndex);
bytes32 lastValueOfListHash = keccak256(abi.encode(lastValueOfList));
setInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, index)), lastValueOfList);
setUInt256(
keccak256(
abi.encodePacked(
INT8_ID,
_listId,
INDEX_POSTFIX,
lastValueOfListHash
)
),
index
);
deleteInt8(keccak256(abi.encodePacked(_listId, VALUES_POSTFIX, lastKeyIndex)));
}
}
| 6,443,284 |
/**
*Submitted for verification at Etherscan.io on 2020-03-29
*/
/**
*Submitted for verification at Etherscan.io on 2019-10-18
*/
pragma solidity ^0.5.5;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask ; //inject UNINIT LOCAL/STATE VAR
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest ; //inject UNINIT LOCAL/STATE VAR
if (other._len < self._len)
shortest = other._len;
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
uint otherptr ; //inject UNINIT LOCAL/STATE VAR
for (uint idx ; idx < shortest; idx += 32) { //inject UNINIT LOCAL/STATE VAR
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask ; // 0xffff... //inject UNINIT LOCAL/STATE VAR
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff ; //inject UNINIT LOCAL/STATE VAR
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor ; //inject UNINIT LOCAL/STATE VAR
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b ; //inject UNINIT LOCAL/STATE VAR
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i ; i < length; i++) { //inject UNINIT LOCAL/STATE VAR
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end ; //inject UNINIT LOCAL/STATE VAR
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length ; //inject UNINIT LOCAL/STATE VAR
for(uint i ; i < parts.length; i++) //inject UNINIT LOCAL/STATE VAR
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i ; i < parts.length; i++) { //inject UNINIT LOCAL/STATE VAR
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* @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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/*
* @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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
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);
}
/**
* @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 {IERC721-safeTransferFrom}. 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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 ; //inject UNINIT LOCAL/STATE VAR
// 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// 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 ; //inject UNINIT LOCAL/STATE VAR
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
/**
* @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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_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), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
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 ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_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), "ERC721: approved query for nonexistent token");
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 != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(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 {IERC721Receiver-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 {IERC721Receiver-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 _msgSender() 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 {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @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) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @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
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @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, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
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);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, 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(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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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), "ERC721Enumerable: owner index out of bounds");
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(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @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 {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @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
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// 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 ; //inject UNINIT LOCAL/STATE VAR
_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
_allTokens.length--;
_allTokensIndex[tokenId] = 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.
*
* 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 ; //inject UNINIT LOCAL/STATE VAR
_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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* Modified to remove the mint function and to replace it
* with the _addTokenTo function.
* This function is very similar to the _mint function, but it
* does not emit a Transfer event
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_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), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
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 ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_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), "ERC721: approved query for nonexistent token");
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 != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(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 {IERC721Receiver-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 {IERC721Receiver-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 _msgSender() 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 {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @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) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
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
*/
function _addTokenTo(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @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, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
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);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* Modified to work with the NoMintERC721 contract
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, 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(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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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), "ERC721Enumerable: owner index out of bounds");
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(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @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 {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @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
*/
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// 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 ; //inject UNINIT LOCAL/STATE VAR
_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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* Modified to change
* function tokenURI(uint256 tokenId) external view returns (string memory);
* to
* function tokenURI(uint256 tokenId) public view returns (string memory);
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* 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;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
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 memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
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 memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @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];
}
}
}
/**
* ERC-721 implementation that allows
* tokens (of the same category) to be minted in batches. Each batch
* contains enough data to generate all
* token ids inside the batch, and to
* generate the tokenURI in the batch
*/
contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable {
using strings for *;
address internal factory;
uint16 public constant maxAllocation = 4000;
uint256 public lastAllocation ; //inject UNINIT LOCAL/STATE VAR
event BatchTransfer(address indexed from, address indexed to, uint256 indexed batchIndex);
struct Batch {
address owner;
uint16 size;
uint8 category;
uint256 startId;
uint256 startTokenId;
}
Batch[] public allBatches;
mapping(address => uint256) unactivatedBalance;
mapping(uint256 => bool) isActivated;
mapping(uint256 => bool) public outOfBatch;
//Used for enumeration
mapping(address => Batch[]) public batchesOwned;
//Batch index to owner batch index
mapping(uint256 => uint256) public ownedBatchIndex;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
uint256 internal _totalSupply;
modifier onlyFactory {
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") {
factory = factoryAddress;
}
function categoryTypeToId(uint8 category, uint256 categoryId) public view returns (uint256) {
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
if (a.category != category)
continue;
uint256 endId ; //inject UNINIT LOCAL/STATE VAR
if (categoryId >= a.startId && categoryId < endId) {
uint256 dif ; //inject UNINIT LOCAL/STATE VAR
return a.startTokenId + dif;
}
}
revert();
}
function fallbackCount(address __owner) public view returns (uint256) {
}
function fallbackIndex(address __owner, uint256 index) public view returns (uint256) {
}
function migrate(uint256 count) public onlyOwner returns (uint256) {
//Empty for interface
}
function migrateSingle() public onlyOwner returns (uint256) {
//Empty for interface
}
function recoverBatch2(uint256 index, uint256 tokenStart, uint256 tokenEnd) public onlyOwner {
}
function migrateBatch(uint256 index) public onlyOwner returns (uint256) {
}
function recoverBatch1(uint256 index) public onlyOwner {
}
/**
* @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) {
return tokenOfOwner(owner)[index];
}
function getBatchCount(address owner) public view returns(uint256) {
return batchesOwned[owner].length;
}
function updateGunFactory(address _factory) public onlyOwner {
}
function getTokensInBatch(address owner, uint256 index) public view returns (uint256[] memory) {
Batch memory a = batchesOwned[owner][index];
uint256[] memory result = new uint256[](a.size);
uint256 pos ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i] && super.ownerOf(i) != owner) {
continue;
}
result[pos] = i;
pos++;
}
require(pos > 0);
uint256 subAmount ; //inject UNINIT LOCAL/STATE VAR
assembly { mstore(result, sub(mload(result), subAmount)) }
return result;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
return allTokens()[index];
}
function allTokens() public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](totalSupply());
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = j;
pos++;
}
}
return result;
}
function tokenOfOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](balanceOf(owner));
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < batchesOwned[owner].length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = batchesOwned[owner][i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[j] && super.ownerOf(j) != owner) {
continue;
}
result[pos] = j;
pos++;
}
}
uint256[] memory fallbackOwned = _tokensOfOwner(owner);
for (uint i ; i < fallbackOwned.length; i++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = fallbackOwned[i];
pos++;
}
return result;
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return super.balanceOf(owner) + unactivatedBalance[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.ownerOf(tokenId);
}
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
return a.owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
if (isActivated[_tokenId]) {
return super._exists(_tokenId);
} else {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
if (index < allBatches.length) {
Batch memory a = allBatches[index];
uint end ; //inject UNINIT LOCAL/STATE VAR
return _tokenId < end;
}
return false;
}
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function claimAllocation(address to, uint16 size, uint8 category) public onlyFactory returns (uint) {
require(size < maxAllocation, "Size must be smaller than maxAllocation");
allBatches.push(Batch({
owner: to,
size: size,
category: category,
startId: totalGunsMintedByCategory[category],
startTokenId: lastAllocation
}));
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
emit Transfer(address(0), to, i);
}
lastAllocation += maxAllocation;
unactivatedBalance[to] += size;
totalGunsMintedByCategory[category] += size;
_addBatchToOwner(to, allBatches[allBatches.length - 1]);
_totalSupply += size;
return lastAllocation;
}
function transferFrom(address from, address to, uint256 tokenId) public {
if (!isActivated[tokenId]) {
activate(tokenId);
}
super.transferFrom(from, to, tokenId);
}
function activate(uint256 tokenId) public {
require(!isActivated[tokenId], "Token already activated");
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
isActivated[tokenId] = true;
addTokenTo(a.owner, tokenId);
unactivatedBalance[a.owner]--;
}
function getBatchIndex(uint256 tokenId) public pure returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
return index;
}
function categoryForToken(uint256 tokenId) public view returns (uint8) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
return a.category;
}
function categoryIdForToken(uint256 tokenId) public view returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
uint256 categoryId ; //inject UNINIT LOCAL/STATE VAR
return categoryId;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.tokenURI(tokenId);
} else {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
return _metadata;
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
super._addTokenTo(_to, _tokenId);
super._setTokenURI(_tokenId, _metadata);
}
function ceil(uint a, uint m) internal pure returns (uint ) {
return ((a + m - 1) / m) * m;
}
function _removeBatchFromOwner(address from, Batch memory batch) 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 globalIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastBatchIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 batchIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (batchIndex != lastBatchIndex) {
Batch memory lastBatch = batchesOwned[from][lastBatchIndex];
uint256 lastGlobalIndex ; //inject UNINIT LOCAL/STATE VAR
batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch
ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index
}
// This also deletes the contents at the last position of the array
batchesOwned[from].length--;
// Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by
// lastBatch, or just over the end of the array if the batch was the last one).
}
function _addBatchToOwner(address to, Batch memory batch) private {
uint256 globalIndex ; //inject UNINIT LOCAL/STATE VAR
ownedBatchIndex[globalIndex] = batchesOwned[to].length;
batchesOwned[to].push(batch);
}
function batchTransfer(uint256 batchIndex, address to) public {
Batch storage a = allBatches[batchIndex];
address previousOwner ; //inject UNINIT LOCAL/STATE VAR
require(a.owner == msg.sender);
_removeBatchFromOwner(previousOwner, a);
a.owner = to;
_addBatchToOwner(to, a);
emit BatchTransfer(previousOwner, to, batchIndex);
//Now to need to emit a bunch of transfer events
uint end ; //inject UNINIT LOCAL/STATE VAR
uint256 unActivated ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i]) {
if (ownerOf(i) != previousOwner)
continue; //The previous owner didn't own this token, don't emit an event
} else {
unActivated++;
}
emit Transfer(previousOwner, to, i);
}
unactivatedBalance[to] += unActivated;
unactivatedBalance[previousOwner] -= unActivated;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool);
}
/**
* @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);
}
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
);
}
contract BurnableToken is ERC20 {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public;
}
contract StandardBurnableToken is BurnableToken {
function burnFrom(address _from, uint256 _value) public;
}
interface BZNFeed {
/**
* Returns the converted BZN value
*/
function convert(uint256 usd) external view returns (uint256);
}
contract SimpleBZNFeed is BZNFeed, Ownable {
uint256 private conversion;
function updateConversion(uint256 conversionRate) public onlyOwner {
conversion = conversionRate;
}
function convert(uint256 usd) external view returns (uint256) {
return usd * conversion;
}
}
interface IDSValue {
function peek() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function poke(bytes32 wut) external;
function void() external;
}
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
contract GunPreOrder is Ownable, ApproveAndCallFallBack {
using BytesLib for bytes;
using SafeMath for uint256;
//Event for when a bulk buy order has been placed
event consumerBulkBuy(uint8 category, uint256 quanity, address reserver);
//Event for when a gun has been bought
event GunsBought(uint256 gunId, address owner, uint8 category);
//Event for when ether is taken out of this contract
event Withdrawal(uint256 amount);
//Default referal commision percent
uint256 public constant COMMISSION_PERCENT = 5;
//Whether category is open
mapping(uint8 => bool) public categoryExists;
mapping(uint8 => bool) public categoryOpen;
mapping(uint8 => bool) public categoryKilled;
//The additional referal commision percent for any given referal address (default is 0)
mapping(address => uint256) internal commissionRate;
//How many guns in a given category an address has reserved
mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount;
//Opensea buy address
address internal constant OPENSEA = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073;
//The percent increase and percent base for a given category
mapping(uint8 => uint256) public categoryPercentIncrease;
mapping(uint8 => uint256) public categoryPercentBase;
//Price of a givevn category in USD WEI
mapping(uint8 => uint256) public categoryPrice;
//The percent of ether required for buying in BZN
mapping(uint8 => uint256) public requiredEtherPercent;
mapping(uint8 => uint256) public requiredEtherPercentBase;
bool public allowCreateCategory ; //inject UNINIT LOCAL/STATE VAR
//The gun token contract
GunToken public token;
//The gun factory contract
GunFactory internal factory;
//The BZN contract
StandardBurnableToken internal bzn;
//The Maker ETH/USD price feed
IDSValue public ethFeed;
BZNFeed public bznFeed;
//The gamepool address
address internal gamePool;
//Require the skinned/regular shop to be opened
modifier ensureShopOpen(uint8 category) {
require(categoryExists[category], "Category doesn't exist!");
require(categoryOpen[category], "Category is not open!");
_;
}
//Allow a function to accept ETH payment
modifier payInETH(address referal, uint8 category, address new_owner, uint16 quanity) {
uint256 usdPrice;
uint256 totalPrice;
(usdPrice, totalPrice) = priceFor(category, quanity);
require(usdPrice > 0, "Price not yet set");
categoryPrice[category] = usdPrice; //Save last price
uint256 price ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= price, "Not enough Ether sent!");
_;
if (msg.value > price) {
uint256 change ; //inject UNINIT LOCAL/STATE VAR
msg.sender.transfer(change);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
uint256 totalCommision ; //inject UNINIT LOCAL/STATE VAR
uint256 commision ; //inject UNINIT LOCAL/STATE VAR
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(commision);
}
}
//Allow function to accept BZN payment
modifier payInBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) {
uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice)
(prices[0], prices[3]) = priceFor(category, quanity);
require(prices[0] > 0, "Price not yet set");
categoryPrice[category] = prices[0];
prices[1] = convert(prices[3], true); //Convert the totalPrice to BZN
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
if (referal != address(0)) {
prices[2] = (prices[1] * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
}
uint256 requiredEther ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= requiredEther, "Buying with BZN requires some Ether!");
bzn.burnFrom(new_owner, (((prices[1] - prices[2]) * 30) / 100));
bzn.transferFrom(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100));
_;
if (msg.value > requiredEther) {
new_owner.transfer(msg.value - requiredEther);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
bzn.transferFrom(new_owner, referal, prices[2]);
prices[2] = (requiredEther * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(prices[2]);
}
}
//Constructor
constructor(
address tokenAddress,
address tokenFactory,
address gp,
address isd,
address bzn_address
) public {
token = GunToken(tokenAddress);
factory = GunFactory(tokenFactory);
ethFeed = IDSValue(isd);
bzn = StandardBurnableToken(bzn_address);
gamePool = gp;
//Set percent increases
categoryPercentIncrease[1] = 100035;
categoryPercentBase[1] = 100000;
categoryPercentIncrease[2] = 100025;
categoryPercentBase[2] = 100000;
categoryPercentIncrease[3] = 100015;
categoryPercentBase[3] = 100000;
commissionRate[OPENSEA] = 10;
}
function createCategory(uint8 category) public onlyOwner {
require(allowCreateCategory);
categoryExists[category] = true;
}
function disableCreateCategories() public onlyOwner {
allowCreateCategory = false;
}
//Set the referal commision rate for an address
function setCommission(address referral, uint256 percent) public onlyOwner {
require(percent > COMMISSION_PERCENT);
require(percent < 95);
percent = percent - COMMISSION_PERCENT;
commissionRate[referral] = percent;
}
//Set the price increase/base for skinned or regular guns
function setPercentIncrease(uint256 increase, uint256 base, uint8 category) public onlyOwner {
require(increase > base);
categoryPercentIncrease[category] = increase;
categoryPercentBase[category] = base;
}
function setEtherPercent(uint256 percent, uint256 base, uint8 category) public onlyOwner {
requiredEtherPercent[category] = percent;
requiredEtherPercentBase[category] = base;
}
function killCategory(uint8 category) public onlyOwner {
require(!categoryKilled[category]);
categoryOpen[category] = false;
categoryKilled[category] = true;
}
//Open/Close the skinned or regular guns shop
function setShopState(uint8 category, bool open) public onlyOwner {
require(category == 1 || category == 2 || category == 3);
require(!categoryKilled[category]);
require(categoryExists[category]);
categoryOpen[category] = open;
}
/**
* Set the price for any given category in USD.
*/
function setPrice(uint8 category, uint256 price, bool inWei) public onlyOwner {
uint256 multiply ; //inject UNINIT LOCAL/STATE VAR
if (inWei) {
multiply = 1;
}
categoryPrice[category] = price * multiply;
}
/**
Withdraw the amount from the contract's balance. Only the contract owner can execute this function
*/
function withdraw(uint256 amount) public onlyOwner {
uint256 balance ; //inject UNINIT LOCAL/STATE VAR
require(amount <= balance, "Requested to much");
address payable _owner ; //inject UNINIT LOCAL/STATE VAR
_owner.transfer(amount);
emit Withdrawal(amount);
}
function setBZNFeedContract(address new_bzn_feed) public onlyOwner {
bznFeed = BZNFeed(new_bzn_feed);
}
//Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) ensureShopOpen(category) payInBZN(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
//Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithEther(address referal, uint8 category, address new_owner, uint16 quanity) ensureShopOpen(category) payInETH(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
function convert(uint256 usdValue, bool isBZN) public view returns (uint256) {
if (isBZN) {
return bznFeed.convert(usdValue);
} else {
bool temp;
bytes32 aaa;
(aaa, temp) = ethFeed.peek();
uint256 priceForEtherInUsdWei ; //inject UNINIT LOCAL/STATE VAR
return usdValue / (priceForEtherInUsdWei / 1e18);
}
}
/**
Get the price for skinned or regular guns in USD (wei)
*/
function priceFor(uint8 category, uint16 quanity) public view returns (uint256, uint256) {
require(quanity > 0);
uint256 percent ; //inject UNINIT LOCAL/STATE VAR
uint256 base ; //inject UNINIT LOCAL/STATE VAR
uint256 currentPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 nextPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 totalPrice ; //inject UNINIT LOCAL/STATE VAR
//We can't use exponents because we'll overflow quickly
//Only for loop :(
for (uint i ; i < quanity; i++) { //inject UNINIT LOCAL/STATE VAR
nextPrice = (currentPrice * percent) / base;
currentPrice = nextPrice;
totalPrice += nextPrice;
}
//Return the next price, as this is the true price
return (nextPrice, totalPrice);
}
//Determine if a tokenId exists (has been sold)
function sold(uint256 _tokenId) public view returns (bool) {
return token.exists(_tokenId);
}
function receiveApproval(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) {
address referal;
uint8 category;
uint16 quanity;
(referal, category, quanity) = abi.decode(data, (address, uint8, uint16));
require(quanity >= 1);
address payable _from ; //inject UNINIT LOCAL/STATE VAR
buyWithBZN(referal, category, _from, quanity);
return true;
}
}
contract GunFactory is Ownable {
using strings for *;
uint8 public constant PREMIUM_CATEGORY = 1;
uint8 public constant MIDGRADE_CATEGORY = 2;
uint8 public constant REGULAR_CATEGORY = 3;
uint256 public constant ONE_MONTH = 2628000;
uint256 public mintedGuns ; //inject UNINIT LOCAL/STATE VAR
address preOrderAddress;
GunToken token;
mapping(uint8 => uint256) internal gunsMintedByCategory;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
mapping(uint8 => uint256) internal firstMonthLimit;
mapping(uint8 => uint256) internal secondMonthLimit;
mapping(uint8 => uint256) internal thirdMonthLimit;
uint256 internal startTime;
mapping(uint8 => uint256) internal currentMonthEnd;
uint256 internal monthOneEnd;
uint256 internal monthTwoEnd;
modifier onlyPreOrder {
require(msg.sender == preOrderAddress, "Not authorized");
_;
}
modifier isInitialized {
require(preOrderAddress != address(0), "No linked preorder");
require(address(token) != address(0), "No linked token");
_;
}
constructor() public {
firstMonthLimit[PREMIUM_CATEGORY] = 5000;
firstMonthLimit[MIDGRADE_CATEGORY] = 20000;
firstMonthLimit[REGULAR_CATEGORY] = 30000;
secondMonthLimit[PREMIUM_CATEGORY] = 2500;
secondMonthLimit[MIDGRADE_CATEGORY] = 10000;
secondMonthLimit[REGULAR_CATEGORY] = 15000;
thirdMonthLimit[PREMIUM_CATEGORY] = 600;
thirdMonthLimit[MIDGRADE_CATEGORY] = 3000;
thirdMonthLimit[REGULAR_CATEGORY] = 6000;
startTime = block.timestamp;
monthOneEnd = startTime + ONE_MONTH;
monthTwoEnd = startTime + ONE_MONTH + ONE_MONTH;
currentMonthEnd[PREMIUM_CATEGORY] = monthOneEnd;
currentMonthEnd[MIDGRADE_CATEGORY] = monthOneEnd;
currentMonthEnd[REGULAR_CATEGORY] = monthOneEnd;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function mintFor(address newOwner, uint16 size, uint8 category) public onlyPreOrder isInitialized returns (uint256) {
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
require(preOrder.categoryExists(category), "Invalid category");
require(!hasReachedLimit(category), "The monthly limit has been reached");
token.claimAllocation(newOwner, size, category);
mintedGuns++;
gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1;
totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1;
}
function hasReachedLimit(uint8 category) internal returns (bool) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
uint256 monthEnd ; //inject UNINIT LOCAL/STATE VAR
//If the current block time is greater than or equal to the end of the month
if (currentTime >= monthEnd) {
//It's a new month, reset all limits
//gunsMintedByCategory[PREMIUM_CATEGORY] = 0;
//gunsMintedByCategory[MIDGRADE_CATEGORY] = 0;
//gunsMintedByCategory[REGULAR_CATEGORY] = 0;
gunsMintedByCategory[category] = 0;
//Set next month end to be equal one month in advance
//do this while the current time is greater than the next month end
while (currentTime >= monthEnd) {
monthEnd = monthEnd + ONE_MONTH;
}
//Finally, update the limit
limit = currentLimit(category);
currentMonthEnd[category] = monthEnd;
}
//Check if the limit has been reached
return gunsMintedByCategory[category] >= limit;
}
function reachedLimit(uint8 category) public view returns (bool) {
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
return gunsMintedByCategory[category] >= limit;
}
function currentLimit(uint8 category) public view returns (uint256) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit;
if (currentTime < monthOneEnd) {
limit = firstMonthLimit[category];
} else if (currentTime < monthTwoEnd) {
limit = secondMonthLimit[category];
} else {
limit = thirdMonthLimit[category];
}
return limit;
}
function setCategoryLimit(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public onlyOwner {
require(firstMonthLimit[category] == 0);
require(secondMonthLimit[category] == 0);
require(thirdMonthLimit[category] == 0);
firstMonthLimit[category] = firstLimit;
secondMonthLimit[category] = secondLimit;
thirdMonthLimit[category] = thirdLimit;
}
/**
Attach the preOrder that will be receiving tokens being marked for sale by the
sellCar function
*/
function attachPreOrder(address dst) public onlyOwner {
require(preOrderAddress == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
preOrderAddress = address(preOrder);
}
/**
Attach the token being used for things
*/
function attachToken(address dst) public onlyOwner {
require(address(token) == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunToken ct ; //inject UNINIT LOCAL/STATE VAR
token = ct;
}
}
|
Gets the owner of the specified token ID. tokenId uint256 ID of the token to query the owner of return address currently marked as the owner of the given token ID/
|
function ownerOf(uint256 tokenId) public view returns (address) {
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
| 13,059,242 |
// File: contracts/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @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 number of decimals for token.
*/
function decimals() external view returns (uint8);
/**
* @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/Arth/IIncentive.sol
//
/// @title incentive contract interface
/// @author Fei Protocol
/// @notice Called by FEI token contract when transferring with an incentivized address
/// @dev should be appointed as a Minter or Burner as needed
interface IIncentiveController {
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
// File: contracts/ERC20/IAnyswapV4Token.sol
//
interface IAnyswapV4Token {
function approveAndCall(
address spender,
uint256 value,
bytes calldata data
) external returns (bool);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function transferWithPermit(
address target,
address to,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (bool);
function Swapin(
bytes32 txhash,
address account,
uint256 amount
) external returns (bool);
function Swapout(uint256 amount, address bindaddr) external returns (bool);
function nonces(address owner) external view returns (uint256);
function permit(
address target,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/Arth/IARTH.sol
//
interface IARTH is IERC20, IAnyswapV4Token {
function addPool(address pool) external;
function removePool(address pool) external;
function setGovernance(address _governance) external;
function poolMint(address who, uint256 amount) external;
function poolBurnFrom(address who, uint256 amount) external;
function setIncentiveController(IIncentiveController _incentiveController)
external;
function genesisSupply() external view returns (uint256);
}
// File: contracts/utils/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;
// 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);
}
}
}
}
// File: contracts/utils/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/utils/math/SafeMath.sol
//
// 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) { 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) {
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) {
{
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) {
{
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;
}
}
}
// File: contracts/access/Ownable.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() {
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;
}
}
// File: contracts/Staking/Pausable.sol
//
/// Refer: https://docs.synthetix.io/contracts/Pausable
abstract contract Pausable is Ownable {
/**
* State variables.
*/
bool public paused;
uint256 public lastPauseTime;
/**
* Event.
*/
event PauseChanged(bool isPaused);
/**
* Modifier.
*/
modifier notPaused {
require(
!paused,
'Pausable: This action cannot be performed while the contract is paused'
);
_;
}
/**
* Constructor.
*/
constructor() {
// This contract is abstract, and thus cannot be instantiated directly
require(owner() != address(0), 'Owner must be set');
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* External.
*/
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = block.timestamp;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
// File: contracts/ERC20/ERC20Custom.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 {ERC20Mintable}.
*
* 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}.
*/
abstract contract ERC20Custom is Pausable, IERC20 {
using SafeMath for uint256;
uint256 private _totalSupply;
mapping(address => bool) internal _blacklisted;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
/**
* Modifiers
*/
modifier onlyNonBlacklisted(address who) {
require(!getIsBlacklisted(who), 'ERC20Custom: address is blacklisted');
_;
}
/**
* Constructor.
*/
constructor() {}
/**
* @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 Returns if an address is blackListed or not.
*/
function getIsBlacklisted(address who) public view returns (bool) {
return _blacklisted[who];
}
/**
* @dev Blacklists an address.
*/
function blacklist(address who) public onlyOwner returns (bool) {
if (getIsBlacklisted(who)) return true;
_blacklisted[who] = true;
return true;
}
/**
* @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.approve(address spender, uint256 amount)
*/
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`.
*
* NOTE: The `spender i.e msg.sender` and the `owner` both should not be blacklisted.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override onlyNonBlacklisted(_msgSender()) 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`.
*
* NOTE: The `sender` should not be blacklisted.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual notPaused onlyNonBlacklisted(sender) {
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.
*
* NOTE: The `account` should not be blacklisted.
*/
function _mint(address account, uint256 amount)
internal
virtual
onlyNonBlacklisted(account)
{
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*
* NOTE: The `account` and `burner i.e msg.sender` both should not be blacklisted.
*/
function burnFrom(address account, uint256 amount)
public
virtual
onlyNonBlacklisted(_msgSender())
{
uint256 decreasedAllowance =
allowance(account, _msgSender()).sub(
amount,
'ERC20: burn amount exceeds allowance'
);
_approve(account, _msgSender(), decreasedAllowance);
_burn(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.
*
* NOTE: The `account` should not be blacklisted.
*/
function _burn(address account, uint256 amount)
internal
virtual
onlyNonBlacklisted(account)
{
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount)
internal
virtual
onlyNonBlacklisted(_msgSender())
{
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
'ERC20: burn amount exceeds allowance'
)
);
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/utils/introspection/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);
}
// File: contracts/utils/introspection/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/access/AccessControl.sol
//
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
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 AccessControl is Context, IAccessControl, ERC165 {
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 See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IAccessControl).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 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 {
require(
hasRole(getRoleAdmin(role), _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 override {
require(
hasRole(getRoleAdmin(role), _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
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());
}
}
}
// File: contracts/ERC20/AnyswapV4Token.sol
interface IApprovalReceiver {
function onTokenApproval(
address,
uint256,
bytes calldata
) external returns (bool);
}
interface ITransferReceiver {
function onTokenTransfer(
address,
uint256,
bytes calldata
) external returns (bool);
}
abstract contract AnyswapV4Token is
ERC20Custom,
AccessControl,
IAnyswapV4Token
{
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant BRIDGE_ROLE = keccak256('BRIDGE_ROLE');
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
bytes32 public constant TRANSFER_TYPEHASH =
keccak256(
'Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)'
);
mapping(address => uint256) public override nonces;
event LogSwapin(
bytes32 indexed txhash,
address indexed account,
uint256 amount
);
event LogSwapout(
address indexed account,
address indexed bindaddr,
uint256 amount
);
modifier onlyBridge {
require(
hasRole(BRIDGE_ROLE, _msgSender()),
'AnyswapV4Token: forbidden'
);
_;
}
constructor(string memory name) {
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function approveAndCall(
address spender,
uint256 value,
bytes calldata data
) external override returns (bool) {
_approve(msg.sender, spender, value);
return
IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data);
}
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf(msg.sender);
require(
balance >= value,
'AnyswapV3ERC20: transfer amount exceeds balance'
);
_transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
function transferWithPermit(
address target,
address to,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override returns (bool) {
require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit');
bytes32 hashStruct =
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline
)
);
require(
_verifyEIP712(target, hashStruct, v, r, s) ||
_verifyPersonalSign(target, hashStruct, v, r, s)
);
// NOTE: is this check needed, was there in the refered contract.
require(to != address(0) || to != address(this));
require(
balanceOf(target) >= value,
'AnyswapV3ERC20: transfer amount exceeds balance'
);
_transfer(target, to, value);
return true;
}
function permit(
address target,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override {
require(block.timestamp <= deadline, 'AnyswapV3ERC20: Expired permit');
bytes32 hashStruct =
keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline
)
);
require(
_verifyEIP712(target, hashStruct, v, r, s) ||
_verifyPersonalSign(target, hashStruct, v, r, s)
);
_approve(target, spender, value);
emit Approval(target, spender, value);
}
/// @dev Only Auth needs to be implemented
function Swapin(
bytes32 txhash,
address account,
uint256 amount
) public override onlyBridge returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr)
public
override
onlyBridge
returns (bool)
{
require(bindaddr != address(0), 'AnyswapV4ERC20: address(0x0)');
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
function _verifyEIP712(
address target,
bytes32 hashStruct,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (bool) {
bytes32 hash =
keccak256(
abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, hashStruct)
);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
/// @dev 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 _verifyPersonalSign(
address target,
bytes32 hashStruct,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (bool) {
bytes32 hash = _prefixed(hashStruct);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
}
// File: contracts/Arth/Arth.sol
//
/**
* @title ARTHStablecoin.
* @author MahaDAO.
*/
contract ARTHStablecoin is AnyswapV4Token, IARTH {
IIncentiveController public incentiveController;
address public governance;
uint8 public constant override decimals = 18;
string public constant symbol = 'ARTH';
string public constant name = 'ARTH Valuecoin';
/// @notice This is to help with establishing the Uniswap pools, as they need liquidity.
uint256 public constant override genesisSupply = 22000000e18; // 22M ARTH (testnet) & 5k (Mainnet).
mapping(address => bool) public pools;
event PoolBurned(address indexed from, address indexed to, uint256 amount);
event PoolMinted(address indexed from, address indexed to, uint256 amount);
modifier onlyPools() {
require(pools[msg.sender] == true, 'ARTH: not pool');
_;
}
modifier onlyByOwnerOrGovernance() {
require(
msg.sender == owner() || msg.sender == governance,
'ARTH: not owner or governance'
);
_;
}
constructor() AnyswapV4Token(name) {
_mint(msg.sender, genesisSupply);
}
/// @notice Used by pools when user redeems.
function poolBurnFrom(address who, uint256 amount)
external
override
onlyPools
{
super._burnFrom(who, amount);
emit PoolBurned(who, msg.sender, amount);
}
/// @notice This function is what other arth pools will call to mint new ARTH
function poolMint(address who, uint256 amount) external override onlyPools {
super._mint(who, amount);
emit PoolMinted(msg.sender, who, amount);
}
/// @dev Collateral Must be ERC20.
/// @notice Adds collateral addresses supported.
function addPool(address pool) external override onlyByOwnerOrGovernance {
require(pools[pool] == false, 'pool exists');
pools[pool] = true;
}
/// @notice Removes a pool.
function removePool(address pool)
external
override
onlyByOwnerOrGovernance
{
require(pools[pool] == true, "pool doesn't exist");
delete pools[pool];
}
function setGovernance(address _governance) external override onlyOwner {
governance = _governance;
}
function setIncentiveController(IIncentiveController _incentiveController)
external
override
onlyByOwnerOrGovernance
{
incentiveController = _incentiveController;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
super._transfer(sender, recipient, amount);
if (address(incentiveController) != address(0)) {
incentiveController.incentivize(
sender,
recipient,
msg.sender,
amount
);
}
}
}
|
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`. NOTE: The `spender i.e msg.sender` and the `owner` both should not be blacklisted./
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override onlyNonBlacklisted(_msgSender()) returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
'ERC20: transfer amount exceeds allowance'
)
);
return true;
}
| 5,378,563 |
./full_match/222000222/0xdf19C1Ee9c3438401B6C8CFE1E4C5885351F569f/sources/contracts/SmartChef.sol
|
Update reward variables of the given pool to be up-to-date./
|
function _updatePool() internal {
if (block.timestamp <= lastRewardTime) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply == 0) {
lastRewardTime = block.timestamp;
return;
}
uint256 multiplier = _getMultiplier(lastRewardTime, block.timestamp);
uint256 reward = multiplier.mul(rewardPerSecond);
accTokenPerShare = accTokenPerShare.add(reward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
lastRewardTime = block.timestamp;
}
| 13,222,111 |
// 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 () {
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.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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
import "./Executor.sol";
import "../interfaces/IDependencyController.sol";
/// @title Provides a single point of reference to verify integrity
/// of the roles structure and facilitate governance actions
/// within our system as well as performing cache invalidation for
/// roles and inter-contract relationships
contract DependencyController is RoleAware, IDependencyController {
constructor(address _roles) RoleAware(_roles) {}
address public override currentExecutor;
address[] public managedContracts;
mapping(uint256 => bool) public knownCharacters;
mapping(uint256 => bool) public knownRoles;
uint256[] public allCharacters;
uint256[] public allRoles;
function executeAsOwner(address executor) external onlyOwnerExec {
uint256[] memory requiredRoles = Executor(executor).requiredRoles();
for (uint256 i = 0; requiredRoles.length > i; i++) {
_giveRole(requiredRoles[i], executor);
}
updateCaches(executor);
currentExecutor = executor;
Executor(executor).execute();
currentExecutor = address(0);
uint256 len = requiredRoles.length;
for (uint256 i = 0; len > i; i++) {
_removeRole(requiredRoles[i], executor);
}
}
/// Orchestrate roles and permission for contract
function manageContract(
address contr,
uint256[] memory charactersPlayed,
uint256[] memory rolesPlayed
) external onlyOwnerExec {
managedContracts.push(contr);
// set up all characters this contract plays
uint256 len = charactersPlayed.length;
for (uint256 i = 0; len > i; i++) {
uint256 character = charactersPlayed[i];
_setMainCharacter(character, contr);
}
// all roles this contract plays
len = rolesPlayed.length;
for (uint256 i = 0; len > i; i++) {
uint256 role = rolesPlayed[i];
_giveRole(role, contr);
}
updateCaches(contr);
}
/// Remove roles and permissions for contract
function disableContract(address contr) external onlyOwnerExecDisabler {
_disableContract(contr);
}
function _disableContract(address contr) internal {
uint256 len = allRoles.length;
for (uint256 i = 0; len > i; i++) {
if (roles.getRole(allRoles[i], contr)) {
_removeRole(allRoles[i], contr);
}
}
len = allCharacters.length;
for (uint256 i = 0; len > i; i++) {
if (roles.mainCharacters(allCharacters[i]) == contr) {
_setMainCharacter(allCharacters[i], address(0));
}
}
}
/// Activate role
function giveRole(uint256 role, address actor) external onlyOwnerExec {
_giveRole(role, actor);
}
/// Disable role
function removeRole(uint256 role, address actor)
external
onlyOwnerExecDisabler
{
_removeRole(role, actor);
}
function _removeRole(uint256 role, address actor) internal {
roles.removeRole(role, actor);
updateRoleCache(role, actor);
}
function setMainCharacter(uint256 role, address actor)
external
onlyOwnerExec
{
_setMainCharacter(role, actor);
}
function _giveRole(uint256 role, address actor) internal {
if (!knownRoles[role]) {
knownRoles[role] = true;
allRoles.push(role);
}
roles.giveRole(role, actor);
updateRoleCache(role, actor);
}
function _setMainCharacter(uint256 character, address actor) internal {
if (!knownCharacters[character]) {
knownCharacters[character] = true;
allCharacters.push(character);
}
roles.setMainCharacter(character, actor);
updateMainCharacterCache(character);
}
function updateMainCharacterCache(uint256 character) public override {
uint256 len = managedContracts.length;
for (uint256 i = 0; len > i; i++) {
RoleAware(managedContracts[i]).updateMainCharacterCache(character);
}
}
function updateRoleCache(uint256 role, address contr) public override {
uint256 len = managedContracts.length;
for (uint256 i = 0; len > i; i++) {
RoleAware(managedContracts[i]).updateRoleCache(role, contr);
}
}
function updateCaches(address contr) public {
// update this contract with all characters we know about
uint256 len = allCharacters.length;
for (uint256 i = 0; len > i; i++) {
RoleAware(contr).updateMainCharacterCache(allCharacters[i]);
}
// update this contract with all roles for all contracts we know about
len = allRoles.length;
for (uint256 i = 0; len > i; i++) {
for (uint256 j = 0; managedContracts.length > j; j++) {
RoleAware(contr).updateRoleCache(
allRoles[i],
managedContracts[j]
);
}
}
}
function allManagedContracts() external view returns (address[] memory) {
return managedContracts;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./RoleAware.sol";
abstract contract Executor is RoleAware {
function requiredRoles() external virtual returns (uint256[] memory);
function execute() external virtual;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./Roles.sol";
/// @title Role management behavior
/// Main characters are for service discovery
/// Whereas roles are for access control
contract RoleAware {
Roles public immutable roles;
mapping(uint256 => address) public mainCharacterCache;
mapping(address => mapping(uint256 => bool)) public roleCache;
constructor(address _roles) {
require(_roles != address(0), "Please provide valid roles address");
roles = Roles(_roles);
}
modifier noIntermediary() {
require(
msg.sender == tx.origin,
"Currently no intermediaries allowed for this function call"
);
_;
}
// @dev Throws if called by any account other than the owner or executor
modifier onlyOwnerExec() {
require(
owner() == msg.sender || executor() == msg.sender,
"Roles: caller is not the owner"
);
_;
}
modifier onlyOwnerExecDisabler() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
disabler() == msg.sender,
"Caller is not the owner, executor or authorized disabler"
);
_;
}
modifier onlyOwnerExecActivator() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
isTokenActivator(msg.sender),
"Caller is not the owner, executor or authorized activator"
);
_;
}
function updateRoleCache(uint256 role, address contr) public virtual {
roleCache[contr][role] = roles.getRole(role, contr);
}
function updateMainCharacterCache(uint256 role) public virtual {
mainCharacterCache[role] = roles.mainCharacters(role);
}
function owner() internal view returns (address) {
return roles.owner();
}
function executor() internal returns (address) {
return roles.executor();
}
function disabler() internal view returns (address) {
return mainCharacterCache[DISABLER];
}
function fund() internal view returns (address) {
return mainCharacterCache[FUND];
}
function lending() internal view returns (address) {
return mainCharacterCache[LENDING];
}
function marginRouter() internal view returns (address) {
return mainCharacterCache[MARGIN_ROUTER];
}
function crossMarginTrading() internal view returns (address) {
return mainCharacterCache[CROSS_MARGIN_TRADING];
}
function feeController() internal view returns (address) {
return mainCharacterCache[FEE_CONTROLLER];
}
function price() internal view returns (address) {
return mainCharacterCache[PRICE_CONTROLLER];
}
function admin() internal view returns (address) {
return mainCharacterCache[ADMIN];
}
function incentiveDistributor() internal view returns (address) {
return mainCharacterCache[INCENTIVE_DISTRIBUTION];
}
function tokenAdmin() internal view returns (address) {
return mainCharacterCache[TOKEN_ADMIN];
}
function isBorrower(address contr) internal view returns (bool) {
return roleCache[contr][BORROWER];
}
function isFundTransferer(address contr) internal view returns (bool) {
return roleCache[contr][FUND_TRANSFERER];
}
function isMarginTrader(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_TRADER];
}
function isFeeSource(address contr) internal view returns (bool) {
return roleCache[contr][FEE_SOURCE];
}
function isMarginCaller(address contr) internal view returns (bool) {
return roleCache[contr][MARGIN_CALLER];
}
function isLiquidator(address contr) internal view returns (bool) {
return roleCache[contr][LIQUIDATOR];
}
function isAuthorizedFundTrader(address contr)
internal
view
returns (bool)
{
return roleCache[contr][AUTHORIZED_FUND_TRADER];
}
function isIncentiveReporter(address contr) internal view returns (bool) {
return roleCache[contr][INCENTIVE_REPORTER];
}
function isTokenActivator(address contr) internal view returns (bool) {
return roleCache[contr][TOKEN_ACTIVATOR];
}
function isStakePenalizer(address contr) internal view returns (bool) {
return roleCache[contr][STAKE_PENALIZER];
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/IDependencyController.sol";
// we chose not to go with an enum
// to make this list easy to extend
uint256 constant FUND_TRANSFERER = 1;
uint256 constant MARGIN_CALLER = 2;
uint256 constant BORROWER = 3;
uint256 constant MARGIN_TRADER = 4;
uint256 constant FEE_SOURCE = 5;
uint256 constant LIQUIDATOR = 6;
uint256 constant AUTHORIZED_FUND_TRADER = 7;
uint256 constant INCENTIVE_REPORTER = 8;
uint256 constant TOKEN_ACTIVATOR = 9;
uint256 constant STAKE_PENALIZER = 10;
uint256 constant FUND = 101;
uint256 constant LENDING = 102;
uint256 constant MARGIN_ROUTER = 103;
uint256 constant CROSS_MARGIN_TRADING = 104;
uint256 constant FEE_CONTROLLER = 105;
uint256 constant PRICE_CONTROLLER = 106;
uint256 constant ADMIN = 107;
uint256 constant INCENTIVE_DISTRIBUTION = 108;
uint256 constant TOKEN_ADMIN = 109;
uint256 constant DISABLER = 1001;
uint256 constant DEPENDENCY_CONTROLLER = 1002;
/// @title Manage permissions of contracts and ownership of everything
/// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during
/// beta and will then be transfered to governance
/// https://github.com/marginswap/governance
contract Roles is Ownable {
mapping(address => mapping(uint256 => bool)) public roles;
mapping(uint256 => address) public mainCharacters;
constructor() Ownable() {
// token activation from the get-go
roles[msg.sender][TOKEN_ACTIVATOR] = true;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwnerExecDepController() {
require(
owner() == msg.sender ||
executor() == msg.sender ||
mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender,
"Roles: caller is not the owner"
);
_;
}
function giveRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = true;
}
function removeRole(uint256 role, address actor)
external
onlyOwnerExecDepController
{
roles[actor][role] = false;
}
function setMainCharacter(uint256 role, address actor)
external
onlyOwnerExecDepController
{
mainCharacters[role] = actor;
}
function getRole(uint256 role, address contr) external view returns (bool) {
return roles[contr][role];
}
/// @dev current executor
function executor() public returns (address exec) {
address depController = mainCharacters[DEPENDENCY_CONTROLLER];
if (depController != address(0)) {
exec = IDependencyController(depController).currentExecutor();
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IDependencyController {
function currentExecutor() external returns (address);
}
|
Orchestrate roles and permission for contract set up all characters this contract plays
|
function manageContract(
address contr,
uint256[] memory charactersPlayed,
uint256[] memory rolesPlayed
) external onlyOwnerExec {
managedContracts.push(contr);
uint256 len = charactersPlayed.length;
for (uint256 i = 0; len > i; i++) {
uint256 character = charactersPlayed[i];
_setMainCharacter(character, contr);
}
for (uint256 i = 0; len > i; i++) {
uint256 role = rolesPlayed[i];
_giveRole(role, contr);
}
updateCaches(contr);
}
| 10,121,083 |
./partial_match/1/0x8Fbc2bD0F023c282EB6913444f26Ec8EC73DE967/sources/src/interfaces/IERC20.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(
address recipient,
uint256 amount
) external returns (bool);
function allowance(
address owner,
address spender
) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| 4,162,729 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./AccessControl.sol";
/**
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @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 == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev The FeeRouter contract defines the fee schedule of AXIA Coin and calculates
* the corresponding receiving amounts for sender, receiver and the foundation account.
*/
contract FeeRouter {
using SafeMath for uint256;
event feeScheduleUpdated(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage);
uint256 internal _senderPercentage;
uint256 internal _foundationPercentage;
uint256 internal _receiverPercentage;
/**
* @dev Creates an instance of `FeeRouter` and initialize fee schedule
*/
constructor () {
_senderPercentage = 0;
_foundationPercentage = 15;
_receiverPercentage = 985;
}
/**
* @dev Update the fee schedule. The percentages should be in thousandths*1000.
* For example, if the desired fee is 2‰, the input should be 2. Three values
* MUST sum up to 1000.
*/
function _updateFeeSchedule(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage) internal {
require(senderPercentage.add(foundationPercentage).add(receiverPercentage) == 1000, "Percentages do not sum up to 1000");
_senderPercentage = senderPercentage;
_foundationPercentage = foundationPercentage;
_receiverPercentage = receiverPercentage;
emit feeScheduleUpdated(_senderPercentage, _foundationPercentage, _receiverPercentage);
}
/**
* @dev Get current fees.
*/
function getFeeSchedule() public view returns( uint256[3] memory) {
return [_senderPercentage, _foundationPercentage, _receiverPercentage];
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _maxTotalSupply;
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.
*/
constructor (string memory name_, string memory symbol_, uint256 maxTotalSupply_) {
_name = name_;
_symbol = symbol_;
_maxTotalSupply = maxTotalSupply_;
_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`).
*/
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}.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*/
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");
_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.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
require(_totalSupply.add(amount) <= _maxTotalSupply, "Can not exceed maxTotalSupply");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*/
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 return maxTotalSupply
*/
function getMaxTotalSupply() public view returns (uint256) {
return _maxTotalSupply;
}
}
contract AXCToken is ERC20, Ownable, FeeRouter, AccessControl {
using SafeMath for uint256;
address private _foundation;
mapping (address => bool) private _exemptedAddresses;
constructor() ERC20("AXIA COIN", "AXC", 72560000000000000000000000000) {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_foundation = msg.sender;
}
/**
* @dev mint a new amout of tokens to an account
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
/**
* @dev mint multiple amounts of tokens to a list of accounts
*/
function multiMint(address[] memory to_list, uint256[] memory amounts) public onlyOwner {
require(to_list.length == amounts.length, "Lengths mismatch");
for (uint256 i = 0; i < to_list.length; i++) {
_mint(to_list[i], amounts[i]);
}
}
/**
* @dev update fee schedule by admin
*/
function updateFeeSchedule(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin");
_updateFeeSchedule(senderPercentage, foundationPercentage, receiverPercentage);
}
/**
* @dev implementation of token transfer
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, _foundation, amount.mul(_foundationPercentage).div(1000));
_transfer(msg.sender, recipient, amount.mul(_receiverPercentage).div(1000));
return true;
}
/**
* @dev update foundation account address
*/
function updateFoundation(address foudnationAddress) public returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin");
_foundation = foudnationAddress;
return true;
}
/**
* @dev returns foundation account address
*/
function getFoundation() public view returns (address){
return _foundation;
}
/**
* @dev sums a list of uint
*/
function _sum(uint256[] memory data) private pure returns (uint256) {
uint256 sum;
for(uint256 i; i < data.length; i++){
sum = sum.add(data[i]);
}
return sum;
}
/**
* @dev return whether a user is exempted
*/
function exempted(address account) view public returns (bool) {
return _exemptedAddresses[account];
}
/**
* @dev add self to exempted addresses
*/
function exemptSelf() public returns (bool) {
_exemptedAddresses[msg.sender] = true;
return true;
}
/**
* @dev remove self from exempted addresses
*/
function revertExemptSelf() public returns (bool) {
delete _exemptedAddresses[msg.sender];
return true;
}
/**
* @dev update a balances for multiple accounts
*/
function batchUpdateBalances(address[] memory to_add_list, uint256[] memory to_add_amounts, address[] memory to_sub_list, uint256[] memory to_sub_amounts) public returns (bool) {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin");
require(_sum(to_add_amounts).sub(_sum(to_sub_amounts), "Not sum up to ZERO") == 0, "Not sum up to ZERO");
require(to_add_list.length == to_add_amounts.length, "Lengths mismatch");
require(to_sub_list.length == to_sub_amounts.length, "Lengths mismatch");
for(uint256 i; i < to_sub_list.length; i++){
require(_exemptedAddresses[to_sub_list[i]] == false, "Exempted");
}
for(uint256 i; i < to_sub_list.length; i++){
_balances[to_sub_list[i]] = _balances[to_sub_list[i]].sub(to_sub_amounts[i], "Batch sub amount exceeds balance");
}
for(uint256 i; i < to_add_list.length; i++){
_balances[to_add_list[i]] = _balances[to_add_list[i]].add(to_add_amounts[i]);
}
return true;
}
/**
* @dev grant admin roles for multiple accounts
*/
function batchGrantAdmin(address[] memory to_grant_list) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || _owner == msg.sender, "Caller is not an admin or owner");
for(uint256 i; i < to_grant_list.length; i++){
_grantRole(DEFAULT_ADMIN_ROLE, to_grant_list[i]);
}
}
/**
* @dev revoke admin roles for multiple accounts
*/
function batchRevokeAdmin(address[] memory to_revoke_list) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || _owner == msg.sender, "Caller is not an admin or owner");
for(uint256 i; i < to_revoke_list.length; i++){
_revokeRole(DEFAULT_ADMIN_ROLE, to_revoke_list[i]);
}
}
}
|
Update the fee schedule. The percentages should be in thousandths1000. For example, if the desired fee is 2‰, the input should be 2. Three values MUST sum up to 1000./
|
function _updateFeeSchedule(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage) internal {
require(senderPercentage.add(foundationPercentage).add(receiverPercentage) == 1000, "Percentages do not sum up to 1000");
_senderPercentage = senderPercentage;
_foundationPercentage = foundationPercentage;
_receiverPercentage = receiverPercentage;
emit feeScheduleUpdated(_senderPercentage, _foundationPercentage, _receiverPercentage);
}
| 5,970 |
pragma solidity ^0.4.25;
library SafeMath
{
function mul(uint a, uint b) internal pure returns (uint)
{
if (a == 0)
{
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint)
{
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint)
{
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC721
{
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns (uint balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint _tokenId) public view returns (address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns (uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
event LogTransfer(address indexed from, address indexed to, uint tokenId);
event LogApproval(address indexed owner, address indexed approved, uint tokenId);
}
contract CryptoCricketToken is ERC721
{
event LogBirth(uint tokenId, string name, uint internalTypeId, uint Price);
event LogSnatch(uint tokenId, string tokenName, address oldOwner, address newOwner, uint oldPrice, uint newPrice);
event LogTransfer(address from, address to, uint tokenId);
string public constant name = "CryptoCricket";
string public constant symbol = "CryptoCricketToken";
uint private commision = 4;
mapping (uint => uint) private startingPrice;
/// @dev A mapping from player IDs to the address that owns them. All players have some valid owner address.
mapping (uint => address) public playerIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns. Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint) private ownershipTokenCount;
/// @dev A mapping from PlayerIDs to an address that has been approved to call transferFrom(). Each Player can only have one approved address for transfer at any time. A zero value means no approval is outstanding.
mapping (uint => address) public playerIndexToApproved;
// @dev A mapping from PlayerIDs to the price of the token.
mapping (uint => uint) private playerIndexToPrice;
// @dev A mapping from PlayerIDs to the reward price of the token obtained while selling.
mapping (uint => uint) private playerIndexToRewardPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public devAddress;
struct Player
{
string name;
uint internalTypeId;
}
Player[] private players;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO()
{
require(msg.sender == ceoAddress);
_;
}
modifier onlyDevORCEO()
{
require(msg.sender == devAddress || msg.sender == ceoAddress);
_;
}
constructor(address _ceo, address _dev) public
{
ceoAddress = _ceo;
devAddress = _dev;
startingPrice[0] = 0.005 ether; // 2x
startingPrice[1] = 0.007 ether; // 2.5x
startingPrice[2] = 0.005 ether; // 1.5x
}
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint _tokenId) public
{
require(owns(msg.sender, _tokenId));
playerIndexToApproved[_tokenId] = _to;
emit LogApproval(msg.sender, _to, _tokenId);
}
function getRewardPrice(uint buyingPrice, uint _internalTypeId) internal view returns(uint rewardPrice)
{
if(_internalTypeId == 0) //Cricket Board Card
{
rewardPrice = SafeMath.div(SafeMath.mul(buyingPrice, 200), 100);
}
else if(_internalTypeId == 1) //Country Card
{
rewardPrice = SafeMath.div(SafeMath.mul(buyingPrice, 250), 100);
}
else //Player Card
{
rewardPrice = SafeMath.div(SafeMath.mul(buyingPrice, 150), 100);
}
rewardPrice = uint(SafeMath.div(SafeMath.mul(rewardPrice, SafeMath.sub(100, commision)), 100));
return rewardPrice;
}
/// For creating Player
function createPlayer(string _name, uint _internalTypeId) public onlyDevORCEO
{
require (_internalTypeId >= 0 && _internalTypeId <= 2);
Player memory _player = Player({name: _name, internalTypeId: _internalTypeId});
uint newPlayerId = players.push(_player) - 1;
playerIndexToPrice[newPlayerId] = startingPrice[_internalTypeId];
playerIndexToRewardPrice[newPlayerId] = getRewardPrice(playerIndexToPrice[newPlayerId], _internalTypeId);
emit LogBirth(newPlayerId, _name, _internalTypeId, startingPrice[_internalTypeId]);
// This will assign ownership, and also emit the Transfer event as per ERC721 draft
_transfer(address(0), address(this), newPlayerId);
}
function payout(address _to) public onlyCEO
{
if(_addressNotNull(_to))
{
_to.transfer(address(this).balance);
}
else
{
ceoAddress.transfer(address(this).balance);
}
}
// Allows someone to send ether and obtain the token
function purchase(uint _tokenId) public payable
{
address oldOwner = playerIndexToOwner[_tokenId];
uint sellingPrice = playerIndexToPrice[_tokenId];
require(oldOwner != msg.sender);
require(_addressNotNull(msg.sender));
require(msg.value >= sellingPrice);
address newOwner = msg.sender;
uint payment = uint(SafeMath.div(SafeMath.mul(sellingPrice, SafeMath.sub(100, commision)), 100));
uint purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
uint _internalTypeId = players[_tokenId].internalTypeId;
if(_internalTypeId == 0) //Cricket Board Card
{
playerIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100);
}
else if(_internalTypeId == 1) //Country Card
{
playerIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 250), 100);
}
else //Player Card
{
playerIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100);
}
_transfer(oldOwner, newOwner, _tokenId);
emit LogSnatch(_tokenId, players[_tokenId].name, oldOwner, newOwner, sellingPrice, playerIndexToPrice[_tokenId]);
playerIndexToRewardPrice[_tokenId] = getRewardPrice(playerIndexToPrice[_tokenId], _internalTypeId);
if (oldOwner != address(this))
{
oldOwner.transfer(payment);
}
msg.sender.transfer(purchaseExcess);
}
/// @param _owner The owner whose soccer player tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Players array looking for players belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint[] ownerTokens)
{
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0)
{
return new uint[](0);
}
else
{
uint[] memory result = new uint[](tokenCount);
uint totalPlayers = totalSupply();
uint resultIndex = 0;
uint playerId;
for (playerId = 0; playerId <= totalPlayers; playerId++)
{
if (playerIndexToOwner[playerId] == _owner)
{
result[resultIndex] = playerId;
resultIndex++;
}
}
return result;
}
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint _tokenId) public
{
require(owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint _tokenId) public
{
require(owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/// @dev Assigns ownership of a specific Player to an address.
function _transfer(address _from, address _to, uint _tokenId) private
{
// Since the number of players is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
playerIndexToOwner[_tokenId] = _to;
// When creating new players _from is 0x0, but we can't account that address.
if (_addressNotNull(_from))
{
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete playerIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit LogTransfer(_from, _to, _tokenId);
}
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool)
{
return (_to != address(0));
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint balance)
{
return ownershipTokenCount[_owner];
}
/// @notice Returns all the relevant information about a specific player.
/// @param _tokenId The tokenId of the player of interest.
function getPlayer(uint _tokenId) public view returns (string playerName, uint internalTypeId, uint sellingPrice, address owner)
{
Player storage player = players[_tokenId];
playerName = player.name;
internalTypeId = player.internalTypeId;
sellingPrice = playerIndexToPrice[_tokenId];
owner = playerIndexToOwner[_tokenId];
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _tokenId) public view returns (address owner)
{
owner = playerIndexToOwner[_tokenId];
require (_addressNotNull(owner));
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint _tokenId) private view returns (bool)
{
return playerIndexToApproved[_tokenId] == _to;
}
/// Check for token ownership
function owns(address claimant, uint _tokenId) private view returns (bool)
{
return (claimant == playerIndexToOwner[_tokenId]);
}
function priceOf(uint _tokenId) public view returns (uint price)
{
return playerIndexToPrice[_tokenId];
}
function rewardPriceOf(uint _tokenId) public view returns (uint price)
{
return playerIndexToRewardPrice[_tokenId];
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO
{
require (_addressNotNull(_newCEO));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the Dev. Only available to the current CEO.
/// @param _newDev The address of the new Dev
function setDev(address _newDev) public onlyCEO
{
require (_addressNotNull(_newDev));
devAddress = _newDev;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint _tokenId) public
{
address newOwner = msg.sender;
address oldOwner = playerIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
/// @dev Assigns a new commison percentage. Only available to the current CEO.
/// @param _newCommision The new commison
function updateCommision (uint _newCommision) public onlyCEO
{
require (_newCommision > 0 && _newCommision < 100);
commision = _newCommision;
}
function implementsERC721() public pure returns (bool)
{
return true;
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint total)
{
return players.length;
}
}
|
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn't hold
|
function div(uint a, uint b) internal pure returns (uint)
{
uint c = a / b;
return c;
}
| 6,470,922 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./interfaces/IOniiChainDescriptor.sol";
import "./interfaces/IOniiChain.sol";
import "./libraries/NFTDescriptor.sol";
import "./libraries/DetailHelper.sol";
import "base64-sol/base64.sol";
/// @title Describes Onii
/// @notice Produces a string containing the data URI for a JSON metadata string
contract OniiChainDescriptor is IOniiChainDescriptor {
/// @dev Max value for defining probabilities
uint256 internal constant MAX = 100000;
uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0];
uint256[] internal SKIN_ITEMS = [2000, 1000, 0];
uint256[] internal NOSE_ITEMS = [10, 0];
uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0];
uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0];
uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0];
uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0];
uint256[] internal ACCESSORY_ITEMS = [
50000,
43000,
36200,
29700,
23400,
17400,
11900,
7900,
4400,
1400,
400,
200,
11,
1,
0
];
uint256[] internal MOUTH_ITEMS = [
80000,
63000,
48000,
36000,
27000,
19000,
12000,
7000,
4000,
2000,
1000,
500,
50,
0
];
uint256[] internal HAIR_ITEMS = [
97000,
94000,
91000,
88000,
85000,
82000,
79000,
76000,
73000,
70000,
67000,
64000,
61000,
58000,
55000,
52000,
49000,
46000,
43000,
40000,
37000,
34000,
31000,
28000,
25000,
22000,
19000,
16000,
13000,
10000,
3000,
1000,
0
];
uint256[] internal EYE_ITEMS = [
98000,
96000,
94000,
92000,
90000,
88000,
86000,
84000,
82000,
80000,
78000,
76000,
74000,
72000,
70000,
68000,
60800,
53700,
46700,
39900,
33400,
27200,
21200,
15300,
10600,
6600,
3600,
2600,
1700,
1000,
500,
100,
10,
0
];
/// @inheritdoc IOniiChainDescriptor
function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) {
NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId);
params.background = getBackgroundId(params);
string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params)));
string memory name = NFTDescriptor.generateName(params, tokenId);
string memory description = NFTDescriptor.generateDescription(params);
string memory attributes = NFTDescriptor.generateAttributes(params);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description":"',
description,
'", "attributes":',
attributes,
', "image": "',
"data:image/svg+xml;base64,",
image,
'"}'
)
)
)
)
);
}
/// @inheritdoc IOniiChainDescriptor
function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId);
}
/// @dev Get SVGParams from OniiChain.Detail
function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) {
IOniiChain.Detail memory detail = oniiChain.details(tokenId);
return
NFTDescriptor.SVGParams({
hair: detail.hair,
eye: detail.eye,
eyebrow: detail.eyebrow,
nose: detail.nose,
mouth: detail.mouth,
mark: detail.mark,
earring: detail.earrings,
accessory: detail.accessory,
mask: detail.mask,
skin: detail.skin,
original: detail.original,
background: 0,
timestamp: detail.timestamp,
creator: detail.creator
});
}
function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) {
uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) +
itemScoreProba(params.accessory, ACCESSORY_ITEMS) +
itemScoreProba(params.earring, EARRINGS_ITEMS) +
itemScoreProba(params.mask, MASK_ITEMS) +
itemScorePosition(params.mouth, MOUTH_ITEMS) +
(itemScoreProba(params.skin, SKIN_ITEMS) / 2) +
itemScoreProba(params.skin, SKIN_ITEMS) +
itemScoreProba(params.nose, NOSE_ITEMS) +
itemScoreProba(params.mark, MARK_ITEMS) +
itemScorePosition(params.eye, EYE_ITEMS) +
itemScoreProba(params.eyebrow, EYEBROW_ITEMS);
return DetailHelper.pickItems(score, BACKGROUND_ITEMS);
}
/// @dev Get item score based on his probability
function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) {
uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]);
return ((raw >= 1000) ? raw * 6 : raw) / 1000;
}
/// @dev Get item score based on his index
function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) {
uint256 raw = ITEMS[item - 1];
return ((raw >= 1000) ? raw * 6 : raw) / 1000;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./IOniiChain.sol";
/// @title Describes Onii via URI
interface IOniiChainDescriptor {
/// @notice Produces the URI describing a particular Onii (token id)
/// @dev Note this URI may be a data: URI with the JSON contents directly inlined
/// @param oniiChain The OniiChain contract
/// @param tokenId The ID of the token for which to produce a description
/// @return The URI of the ERC721-compliant metadata
function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory);
/// @notice Generate randomly an ID for the hair item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the hair item id
function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the eye item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the eye item id
function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the eyebrow item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the eyebrow item id
function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the nose item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the nose item id
function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mouth item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mouth item id
function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mark item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mark item id
function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the earrings item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the earrings item id
function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the accessory item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the accessory item id
function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mask item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mask item id
function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly the skin colors
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the skin item id
function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
/// @title OniiChain NFTs Interface
interface IOniiChain {
/// @notice Details about the Onii
struct Detail {
uint8 hair;
uint8 eye;
uint8 eyebrow;
uint8 nose;
uint8 mouth;
uint8 mark;
uint8 earrings;
uint8 accessory;
uint8 mask;
uint8 skin;
bool original;
uint256 timestamp;
address creator;
}
/// @notice Returns the details associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the Onii
/// @return detail memory
function details(uint256 tokenId) external view returns (Detail memory detail);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./details/BackgroundDetail.sol";
import "./details/BodyDetail.sol";
import "./details/HairDetail.sol";
import "./details/MouthDetail.sol";
import "./details/NoseDetail.sol";
import "./details/EyesDetail.sol";
import "./details/EyebrowDetail.sol";
import "./details/MarkDetail.sol";
import "./details/AccessoryDetail.sol";
import "./details/EarringsDetail.sol";
import "./details/MaskDetail.sol";
import "./DetailHelper.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/// @notice Helper to generate SVGs
library NFTDescriptor {
struct SVGParams {
uint8 hair;
uint8 eye;
uint8 eyebrow;
uint8 nose;
uint8 mouth;
uint8 mark;
uint8 earring;
uint8 accessory;
uint8 mask;
uint8 background;
uint8 skin;
bool original;
uint256 timestamp;
address creator;
}
/// @dev Combine all the SVGs to generate the final image
function generateSVGImage(SVGParams memory params) internal view returns (string memory) {
return
string(
abi.encodePacked(
generateSVGHead(),
DetailHelper.getDetailSVG(address(BackgroundDetail), params.background),
generateSVGFace(params),
DetailHelper.getDetailSVG(address(EarringsDetail), params.earring),
DetailHelper.getDetailSVG(address(HairDetail), params.hair),
DetailHelper.getDetailSVG(address(MaskDetail), params.mask),
DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory),
generateCopy(params.original),
"</svg>"
)
);
}
/// @dev Combine face items
function generateSVGFace(SVGParams memory params) private view returns (string memory) {
return
string(
abi.encodePacked(
DetailHelper.getDetailSVG(address(BodyDetail), params.skin),
DetailHelper.getDetailSVG(address(MarkDetail), params.mark),
DetailHelper.getDetailSVG(address(MouthDetail), params.mouth),
DetailHelper.getDetailSVG(address(NoseDetail), params.nose),
DetailHelper.getDetailSVG(address(EyesDetail), params.eye),
DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow)
)
);
}
/// @dev generate Json Metadata name
function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) {
return
string(
abi.encodePacked(
BackgroundDetail.getItemNameById(params.background),
" Onii ",
Strings.toString(tokenId)
)
);
}
/// @dev generate Json Metadata description
function generateDescription(SVGParams memory params) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"Generated by ",
Strings.toHexString(uint256(uint160(params.creator))),
" at ",
Strings.toString(params.timestamp)
)
);
}
/// @dev generate SVG header
function generateSVGHead() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"',
' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">'
)
);
}
/// @dev generate the "Copy" SVG if the onii is not the original
function generateCopy(bool original) private pure returns (string memory) {
return
!original
? string(
abi.encodePacked(
'<g id="Copy">',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>',
"</g>"
)
)
: "";
}
/// @dev generate Json Metadata attributes
function generateAttributes(SVGParams memory params) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"[",
getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false),
getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false),
getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false),
getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false),
getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false),
getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false),
abi.encodePacked(
getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false),
getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false),
getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false),
getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false),
getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false),
getJsonAttribute("Original", params.original ? "true" : "false", true),
"]"
)
)
);
}
/// @dev Get the json attribute as
/// {
/// "trait_type": "Skin",
/// "value": "Human"
/// }
function getJsonAttribute(
string memory trait,
string memory value,
bool end
) private pure returns (string memory json) {
return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ","));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title Helper for details generation
library DetailHelper {
/// @notice Call the library item function
/// @param lib The library address
/// @param id The item ID
function getDetailSVG(address lib, uint8 id) internal view returns (string memory) {
(bool success, bytes memory data) = lib.staticcall(
abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()")))
);
require(success);
return abi.decode(data, (string));
}
/// @notice Generate a random number and return the index from the
/// corresponding interval.
/// @param max The maximum value to generate
/// @param seed Used for the initialization of the number generator
/// @param intervals the intervals
/// @param selector Caller selector
/// @param tokenId the current tokenId
function generate(
uint256 max,
uint256 seed,
uint256[] memory intervals,
bytes4 selector,
uint256 tokenId
) internal view returns (uint8) {
uint256 generated = generateRandom(max, seed, tokenId, selector);
return pickItems(generated, intervals);
}
/// @notice Generate random number between 1 and max
/// @param max Maximum value of the random number
/// @param seed Used for the initialization of the number generator
/// @param tokenId Current tokenId used as seed
/// @param selector Caller selector used as seed
function generateRandom(
uint256 max,
uint256 seed,
uint256 tokenId,
bytes4 selector
) private view returns (uint256) {
return
(uint256(
keccak256(
abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId)
)
) % (max + 1)) + 1;
}
/// @notice Pick an item for the given random value
/// @param val The random value
/// @param intervals The intervals for the corresponding items
/// @return the item ID where : intervals[] index + 1 = item ID
function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) {
for (uint256 i; i < intervals.length; i++) {
if (val > intervals[i]) {
return SafeCast.toUint8(i + 1);
}
}
revert("DetailHelper::pickItems: No item");
}
}
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Background SVG generator
library BackgroundDetail {
/// @dev background N°1 => Ordinary
function item_1() public pure returns (string memory) {
return base("636363", "CFCFCF", "ABABAB");
}
/// @dev background N°2 => Unusual
function item_2() public pure returns (string memory) {
return base("004A06", "61E89B", "12B55F");
}
/// @dev background N°3 => Surprising
function item_3() public pure returns (string memory) {
return base("1A4685", "6BF0E3", "00ADC7");
}
/// @dev background N°4 => Impressive
function item_4() public pure returns (string memory) {
return base("380113", "D87AE6", "8A07BA");
}
/// @dev background N°5 => Extraordinary
function item_5() public pure returns (string memory) {
return base("A33900", "FAF299", "FF9121");
}
/// @dev background N°6 => Phenomenal
function item_6() public pure returns (string memory) {
return base("000000", "C000E8", "DED52C");
}
/// @dev background N°7 => Artistic
function item_7() public pure returns (string memory) {
return base("FF00E3", "E8E18B", "00C4AD");
}
/// @dev background N°8 => Unreal
function item_8() public pure returns (string memory) {
return base("CCCC75", "54054D", "001E2E");
}
/// @notice Return the background name of the given id
/// @param id The background Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Ordinary";
} else if (id == 2) {
name = "Unusual";
} else if (id == 3) {
name = "Surprising";
} else if (id == 4) {
name = "Impressive";
} else if (id == 5) {
name = "Extraordinary";
} else if (id == 6) {
name = "Phenomenal";
} else if (id == 7) {
name = "Artistic";
} else if (id == 8) {
name = "Unreal";
}
}
/// @dev The base SVG for the backgrounds
function base(
string memory stop1,
string memory stop2,
string memory stop3
) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g id="Background">',
'<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">',
"<style>",
".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}",
"@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}",
"</style>",
"<stop offset='0' class='color-anim' style='stop-color:#",
stop1,
"'/>",
"<stop offset='0.66' style='stop-color:#",
stop2,
"'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>",
"<stop offset='1' style='stop-color:#",
stop3,
"'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>",
abi.encodePacked(
"</radialGradient>",
'<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>',
'<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>',
'<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>',
"</g>"
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Body SVG generator
library BodyDetail {
/// @dev Body N°1 => Human
function item_1() public pure returns (string memory) {
return base("FFEBB4", "FFBE94");
}
/// @dev Body N°2 => Shadow
function item_2() public pure returns (string memory) {
return base("2d2d2d", "000000");
}
/// @dev Body N°3 => Light
function item_3() public pure returns (string memory) {
return base("ffffff", "696969");
}
/// @notice Return the skin name of the given id
/// @param id The skin Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Human";
} else if (id == 2) {
name = "Shadow";
} else if (id == 3) {
name = "Light";
}
}
/// @dev The base SVG for the body
function base(string memory skin, string memory shadow) private pure returns (string memory) {
string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#";
string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'";
return
string(
abi.encodePacked(
'<g id="Body">',
pathBase,
skin,
strokeBase,
" d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>",
abi.encodePacked(
pathBase,
shadow,
"' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>",
pathBase,
skin,
strokeBase,
" d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>",
pathBase
),
skin,
strokeBase,
" d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>",
abi.encodePacked(
pathBase,
skin,
strokeBase,
" d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>",
"<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#",
skin,
"' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>",
"<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>",
"<path fill='#",
shadow
),
"' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>",
"</g>"
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Hair SVG generator
library HairDetail {
/// @dev Hair N°1 => Classic Brown
function item_1() public pure returns (string memory) {
return base(classicHairs(Colors.BROWN));
}
/// @dev Hair N°2 => Classic Black
function item_2() public pure returns (string memory) {
return base(classicHairs(Colors.BLACK));
}
/// @dev Hair N°3 => Classic Gray
function item_3() public pure returns (string memory) {
return base(classicHairs(Colors.GRAY));
}
/// @dev Hair N°4 => Classic White
function item_4() public pure returns (string memory) {
return base(classicHairs(Colors.WHITE));
}
/// @dev Hair N°5 => Classic Blue
function item_5() public pure returns (string memory) {
return base(classicHairs(Colors.BLUE));
}
/// @dev Hair N°6 => Classic Yellow
function item_6() public pure returns (string memory) {
return base(classicHairs(Colors.YELLOW));
}
/// @dev Hair N°7 => Classic Pink
function item_7() public pure returns (string memory) {
return base(classicHairs(Colors.PINK));
}
/// @dev Hair N°8 => Classic Red
function item_8() public pure returns (string memory) {
return base(classicHairs(Colors.RED));
}
/// @dev Hair N°9 => Classic Purple
function item_9() public pure returns (string memory) {
return base(classicHairs(Colors.PURPLE));
}
/// @dev Hair N°10 => Classic Green
function item_10() public pure returns (string memory) {
return base(classicHairs(Colors.GREEN));
}
/// @dev Hair N°11 => Classic Saiki
function item_11() public pure returns (string memory) {
return base(classicHairs(Colors.SAIKI));
}
/// @dev Hair N°12 => Classic 2 Brown
function item_12() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BROWN));
}
/// @dev Hair N°13 => Classic 2 Black
function item_13() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BLACK));
}
/// @dev Hair N°14 => Classic 2 Gray
function item_14() public pure returns (string memory) {
return base(classicTwoHairs(Colors.GRAY));
}
/// @dev Hair N°15 => Classic 2 White
function item_15() public pure returns (string memory) {
return base(classicTwoHairs(Colors.WHITE));
}
/// @dev Hair N°16 => Classic 2 Blue
function item_16() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BLUE));
}
/// @dev Hair N°17 => Classic 2 Yellow
function item_17() public pure returns (string memory) {
return base(classicTwoHairs(Colors.YELLOW));
}
/// @dev Hair N°18 => Classic 2 Pink
function item_18() public pure returns (string memory) {
return base(classicTwoHairs(Colors.PINK));
}
/// @dev Hair N°19 => Classic 2 Red
function item_19() public pure returns (string memory) {
return base(classicTwoHairs(Colors.RED));
}
/// @dev Hair N°20 => Classic 2 Purple
function item_20() public pure returns (string memory) {
return base(classicTwoHairs(Colors.PURPLE));
}
/// @dev Hair N°21 => Classic 2 Green
function item_21() public pure returns (string memory) {
return base(classicTwoHairs(Colors.GREEN));
}
/// @dev Hair N°22 => Classic 2 Saiki
function item_22() public pure returns (string memory) {
return base(classicTwoHairs(Colors.SAIKI));
}
/// @dev Hair N°23 => Short Black
function item_23() public pure returns (string memory) {
return base(shortHairs(Colors.BLACK));
}
/// @dev Hair N°24 => Short Blue
function item_24() public pure returns (string memory) {
return base(shortHairs(Colors.BLUE));
}
/// @dev Hair N°25 => Short Pink
function item_25() public pure returns (string memory) {
return base(shortHairs(Colors.PINK));
}
/// @dev Hair N°26 => Short White
function item_26() public pure returns (string memory) {
return base(shortHairs(Colors.WHITE));
}
/// @dev Hair N°27 => Spike Black
function item_27() public pure returns (string memory) {
return base(spike(Colors.BLACK));
}
/// @dev Hair N°28 => Spike Blue
function item_28() public pure returns (string memory) {
return base(spike(Colors.BLUE));
}
/// @dev Hair N°29 => Spike Pink
function item_29() public pure returns (string memory) {
return base(spike(Colors.PINK));
}
/// @dev Hair N°30 => Spike White
function item_30() public pure returns (string memory) {
return base(spike(Colors.WHITE));
}
/// @dev Hair N°31 => Monk
function item_31() public pure returns (string memory) {
return base(monk());
}
/// @dev Hair N°32 => Nihon
function item_32() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
monk(),
'<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>',
'<g opacity="0.33">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>",
'<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>',
'<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>',
'<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>',
'<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>'
)
)
);
}
/// @dev Hair N°33 => Bald
function item_33() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>'
)
)
);
}
/// @dev Generate classic hairs with the given color
function classicHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>",
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>',
'<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>',
'<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>',
'<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>',
'<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>',
'<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>',
'<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>',
abi.encodePacked(
'<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>',
'<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>',
'<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>',
'<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>',
'<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>',
'<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>',
'<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>',
'<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>',
'<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>'
)
)
);
}
/// @dev Generate classic 2 hairs with the given color
function classicTwoHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<polygon fill='#",
hairsColor,
"' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>",
'<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>',
"<path fill='#",
hairsColor,
"' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>",
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>',
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>',
'<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>',
'<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>',
'<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>',
'<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>',
'<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>'
),
abi.encodePacked(
'<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>',
'<g opacity="0.76">',
'<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>',
'<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>',
'<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>',
'<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>',
'<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>',
'<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>',
'<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>',
'<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>',
"</g>"
)
)
);
}
/// @dev Generate mohawk with the given color
function spike(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>",
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>',
crop()
)
);
}
function shortHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>",
'<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>',
'<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>',
'<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>',
crop()
)
);
}
/// @dev Generate crop SVG
function crop() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g id="Light" opacity="0.14">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>",
'<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>',
'<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>'
)
);
}
/// @dev Generate monk SVG
function monk() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>',
'<g id="Bald" opacity="0.33">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>"
)
);
}
/// @notice Return the hair cut name of the given id
/// @param id The hair Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic Brown";
} else if (id == 2) {
name = "Classic Black";
} else if (id == 3) {
name = "Classic Gray";
} else if (id == 4) {
name = "Classic White";
} else if (id == 5) {
name = "Classic Blue";
} else if (id == 6) {
name = "Classic Yellow";
} else if (id == 7) {
name = "Classic Pink";
} else if (id == 8) {
name = "Classic Red";
} else if (id == 9) {
name = "Classic Purple";
} else if (id == 10) {
name = "Classic Green";
} else if (id == 11) {
name = "Classic Saiki";
} else if (id == 12) {
name = "Classic Brown";
} else if (id == 13) {
name = "Classic 2 Black";
} else if (id == 14) {
name = "Classic 2 Gray";
} else if (id == 15) {
name = "Classic 2 White";
} else if (id == 16) {
name = "Classic 2 Blue";
} else if (id == 17) {
name = "Classic 2 Yellow";
} else if (id == 18) {
name = "Classic 2 Pink";
} else if (id == 19) {
name = "Classic 2 Red";
} else if (id == 20) {
name = "Classic 2 Purple";
} else if (id == 21) {
name = "Classic 2 Green";
} else if (id == 22) {
name = "Classic 2 Saiki";
} else if (id == 23) {
name = "Short Black";
} else if (id == 24) {
name = "Short Blue";
} else if (id == 25) {
name = "Short Pink";
} else if (id == 26) {
name = "Short White";
} else if (id == 27) {
name = "Spike Black";
} else if (id == 28) {
name = "Spike Blue";
} else if (id == 29) {
name = "Spike Pink";
} else if (id == 30) {
name = "Spike White";
} else if (id == 31) {
name = "Monk";
} else if (id == 32) {
name = "Nihon";
} else if (id == 33) {
name = "Bald";
}
}
/// @dev The base SVG for the hair
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Hair">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Mouth SVG generator
library MouthDetail {
/// @dev Mouth N°1 => Neutral
function item_1() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>',
'<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>',
'<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>'
)
)
);
}
/// @dev Mouth N°2 => Smile
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>',
'<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>',
'<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>'
)
)
);
}
/// @dev Mouth N°3 => Sulk
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>'
)
)
);
}
/// @dev Mouth N°4 => Poker
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>'
)
)
);
}
/// @dev Mouth N°5 => Angry
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>',
'<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>',
'<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>'
)
)
);
}
/// @dev Mouth N°6 => Big Smile
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>'
)
)
);
}
/// @dev Mouth N°7 => Evil
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>',
'<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>',
'<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>'
)
)
);
}
/// @dev Mouth N°8 => Tongue
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>',
'<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>'
)
)
);
}
/// @dev Mouth N°9 => Drool
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>'
)
)
);
}
/// @dev Mouth N°10 => O
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>'
)
)
);
}
/// @dev Mouth N°11 => Dubu
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>'
)
)
);
}
/// @dev Mouth N°12 => Stitch
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>',
'<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>',
'<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>',
'<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>',
"</g>"
)
)
);
}
/// @dev Mouth N°13 => Uwu
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>',
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>'
)
)
);
}
/// @dev Mouth N°14 => Monster
function item_14() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>',
'<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>'
)
)
);
}
/// @notice Return the mouth name of the given id
/// @param id The mouth Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Neutral";
} else if (id == 2) {
name = "Smile";
} else if (id == 3) {
name = "Sulk";
} else if (id == 4) {
name = "Poker";
} else if (id == 5) {
name = "Angry";
} else if (id == 6) {
name = "Big Smile";
} else if (id == 7) {
name = "Evil";
} else if (id == 8) {
name = "Tongue";
} else if (id == 9) {
name = "Drool";
} else if (id == 10) {
name = "O";
} else if (id == 11) {
name = "Dubu";
} else if (id == 12) {
name = "Stitch";
} else if (id == 13) {
name = "Uwu";
} else if (id == 14) {
name = "Monster";
}
}
/// @dev The base SVG for the mouth
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mouth">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Nose SVG generator
library NoseDetail {
/// @dev Nose N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Nose N°2 => Bleeding
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>',
'<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>',
'<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>'
)
)
);
}
/// @notice Return the nose name of the given id
/// @param id The nose Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Bleeding";
}
}
/// @dev The base SVG for the Nose
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Eyes SVG generator
library EyesDetail {
/// @dev Eyes N°1 => Color White/Brown
function item_1() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN);
}
/// @dev Eyes N°2 => Color White/Gray
function item_2() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY);
}
/// @dev Eyes N°3 => Color White/Blue
function item_3() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE);
}
/// @dev Eyes N°4 => Color White/Green
function item_4() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN);
}
/// @dev Eyes N°5 => Color White/Black
function item_5() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP);
}
/// @dev Eyes N°6 => Color White/Yellow
function item_6() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW);
}
/// @dev Eyes N°7 => Color White/Red
function item_7() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED);
}
/// @dev Eyes N°8 => Color White/Purple
function item_8() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE);
}
/// @dev Eyes N°9 => Color White/Pink
function item_9() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK);
}
/// @dev Eyes N°10 => Color White/White
function item_10() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE);
}
/// @dev Eyes N°11 => Color Black/Blue
function item_11() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE);
}
/// @dev Eyes N°12 => Color Black/Yellow
function item_12() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW);
}
/// @dev Eyes N°13 => Color Black/White
function item_13() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE);
}
/// @dev Eyes N°14 => Color Black/Red
function item_14() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED);
}
/// @dev Eyes N°15 => Blank White/White
function item_15() public pure returns (string memory) {
return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE);
}
/// @dev Eyes N°16 => Blank Black/White
function item_16() public pure returns (string memory) {
return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE);
}
/// @dev Eyes N°17 => Shine (no-fill)
function item_17() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>',
'<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>'
)
)
);
}
/// @dev Eyes N°18 => Stun (no-fill)
function item_18() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>',
'<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>'
)
)
);
}
/// @dev Eyes N°19 => Squint (no-fill)
function item_19() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>',
'<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>'
)
)
);
}
/// @dev Eyes N°20 => Shock (no-fill)
function item_20() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>'
)
)
);
}
/// @dev Eyes N°21 => Cat (no-fill)
function item_21() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>',
'<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>'
)
)
);
}
/// @dev Eyes N°22 => Ether (no-fill)
function item_22() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>',
'<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>',
'<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>',
'<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>',
'<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>',
'<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>'
)
)
);
}
/// @dev Eyes N°23 => Feels
function item_23() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>',
'<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>',
'<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>',
'<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>',
'<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>',
'<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>'
)
)
);
}
/// @dev Eyes N°24 => Happy
function item_24() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>',
'<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>',
'<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>',
'<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>',
'<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>',
'<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>',
'<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>',
'<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>',
'<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>',
'<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>'
)
)
);
}
/// @dev Eyes N°25 => Arrow
function item_25() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>',
'<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>'
)
)
);
}
/// @dev Eyes N°26 => Closed
function item_26() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>',
'<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>'
)
)
);
}
/// @dev Eyes N°27 => Suspicious
function item_27() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>',
'<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>',
'<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>',
'<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>',
'<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>',
'<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>',
'<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>',
'<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>',
'<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>',
abi.encodePacked(
'<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>',
'<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>',
'<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>'
)
)
)
);
}
/// @dev Eyes N°28 => Annoyed 1
function item_28() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>'
)
)
);
}
/// @dev Eyes N°29 => Annoyed 2
function item_29() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>'
)
)
);
}
/// @dev Eyes N°30 => RIP
function item_30() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>'
)
)
);
}
/// @dev Eyes N°31 => Heart
function item_31() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>',
'<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>'
)
)
);
}
/// @dev Eyes N°32 => Scribble
function item_32() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>',
'<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>'
)
)
);
}
/// @dev Eyes N°33 => Wide
function item_33() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>',
'<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>',
'<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>',
'<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>'
)
)
);
}
/// @dev Eyes N°34 => Dubu
function item_34() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>'
)
)
);
}
/// @dev Right and left eyes (color pupils + eyes)
function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor)
private
pure
returns (string memory)
{
return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor))));
}
/// @dev Right and left eyes (blank pupils + eyes)
function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor)
private
pure
returns (string memory)
{
return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor))));
}
/// @dev Right and left eyes
function eyesNoFill(string memory scleraColor) private pure returns (string memory) {
return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor)));
}
/// @dev Eye right and no fill
function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
scleraColor,
"' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>",
'<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>',
'<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>',
'<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>',
'<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>',
'<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>'
)
);
}
/// @dev Eye right and no fill
function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
scleraColor,
"' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>",
'<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>',
'<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>',
'<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>',
'<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>',
'<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>'
)
);
}
/// @dev Generate color pupils
function colorPupils(string memory pupilsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
pupilsColor,
"' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>",
'<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>',
'<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>',
"<path fill='#",
pupilsColor,
"' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>",
'<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>',
'<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>'
)
);
}
/// @dev Generate blank pupils
function blankPupils(string memory pupilsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
abi.encodePacked(
"<path fill='#",
pupilsColor,
"' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>",
"<path fill='#",
pupilsColor,
"' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>"
)
)
);
}
/// @notice Return the eyes name of the given id
/// @param id The eyes Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Color White/Brown";
} else if (id == 2) {
name = "Color White/Gray";
} else if (id == 3) {
name = "Color White/Blue";
} else if (id == 4) {
name = "Color White/Green";
} else if (id == 5) {
name = "Color White/Black";
} else if (id == 6) {
name = "Color White/Yellow";
} else if (id == 7) {
name = "Color White/Red";
} else if (id == 8) {
name = "Color White/Purple";
} else if (id == 9) {
name = "Color White/Pink";
} else if (id == 10) {
name = "Color White/White";
} else if (id == 11) {
name = "Color Black/Blue";
} else if (id == 12) {
name = "Color Black/Yellow";
} else if (id == 13) {
name = "Color Black/White";
} else if (id == 14) {
name = "Color Black/Red";
} else if (id == 15) {
name = "Blank White/White";
} else if (id == 16) {
name = "Blank Black/White";
} else if (id == 17) {
name = "Shine";
} else if (id == 18) {
name = "Stunt";
} else if (id == 19) {
name = "Squint";
} else if (id == 20) {
name = "Shock";
} else if (id == 21) {
name = "Cat";
} else if (id == 22) {
name = "Ether";
} else if (id == 23) {
name = "Feels";
} else if (id == 24) {
name = "Happy";
} else if (id == 25) {
name = "Arrow";
} else if (id == 26) {
name = "Closed";
} else if (id == 27) {
name = "Suspicious";
} else if (id == 28) {
name = "Annoyed 1";
} else if (id == 29) {
name = "Annoyed 2";
} else if (id == 30) {
name = "RIP";
} else if (id == 31) {
name = "Heart";
} else if (id == 32) {
name = "Scribble";
} else if (id == 33) {
name = "Wide";
} else if (id == 34) {
name = "Dubu";
}
}
/// @dev The base SVG for the eyes
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Eyes">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Eyebrow SVG generator
library EyebrowDetail {
/// @dev Eyebrow N°1 => Classic
function item_1() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>',
'<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>'
)
)
);
}
/// @dev Eyebrow N°2 => Thick
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>'
)
)
);
}
/// @dev Eyebrow N°3 => Punk
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>'
)
)
);
}
/// @dev Eyebrow N°4 => Small
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>'
)
)
);
}
/// @dev Eyebrow N°5 => Shaved
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.06">',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>',
"</g>"
)
)
);
}
/// @dev Eyebrow N°6 => Elektric
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>'
)
)
);
}
/// @notice Return the eyebrow name of the given id
/// @param id The eyebrow Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Thick";
} else if (id == 3) {
name = "Punk";
} else if (id == 4) {
name = "Small";
} else if (id == 5) {
name = "Shaved";
} else if (id == 6) {
name = "Elektric";
}
}
/// @dev The base SVG for the Eyebrow
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Mark SVG generator
library MarkDetail {
/// @dev Mark N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Mark N°2 => Blush Cheeks
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.71">',
'<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>',
'<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>',
"</g>"
)
)
);
}
/// @dev Mark N°3 => Dark Circle
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>',
'<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>',
'<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>',
'<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>'
)
)
);
}
/// @dev Mark N°4 => Chin scar
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>',
'<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>'
)
)
);
}
/// @dev Mark N°5 => Blush
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>'
)
)
);
}
/// @dev Mark N°6 => Chin
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>'
)
)
);
}
/// @dev Mark N°7 => Yinyang
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>'
)
)
);
}
/// @dev Mark N°8 => Scar
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>'
)
)
);
}
/// @dev Mark N°9 => Sun
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>',
'<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>',
'<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>',
'<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>',
'<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>',
'<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>',
'<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>',
'<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>',
'<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>'
)
)
);
}
/// @dev Mark N°10 => Moon
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>'
)
)
);
}
/// @dev Mark N°11 => Third Eye
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>',
'<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>',
'<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>',
'<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>',
'<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>',
'<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>'
)
)
);
}
/// @dev Mark N°12 => Tori
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>',
'<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>',
'<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>'
)
)
);
}
/// @dev Mark N°13 => Ether
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>'
)
)
);
}
/// @notice Return the mark name of the given id
/// @param id The mark Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Blush Cheeks";
} else if (id == 3) {
name = "Dark Circle";
} else if (id == 4) {
name = "Chin Scar";
} else if (id == 5) {
name = "Blush";
} else if (id == 6) {
name = "Chin";
} else if (id == 7) {
name = "Yinyang";
} else if (id == 8) {
name = "Scar";
} else if (id == 9) {
name = "Sun";
} else if (id == 10) {
name = "Moon";
} else if (id == 11) {
name = "Third Eye";
} else if (id == 12) {
name = "Tori";
} else if (id == 13) {
name = "Ether";
}
}
/// @dev The base SVG for the hair
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mark">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Accessory SVG generator
library AccessoryDetail {
/// @dev Accessory N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Accessory N°2 => Glasses
function item_2() public pure returns (string memory) {
return base(glasses("D1F5FF", "000000", "0.31"));
}
/// @dev Accessory N°3 => Bow Tie
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>',
'<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>',
'<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>',
'<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>'
)
)
);
}
/// @dev Accessory N°4 => Monk Beads Classic
function item_4() public pure returns (string memory) {
return base(monkBeads("63205A"));
}
/// @dev Accessory N°5 => Monk Beads Silver
function item_5() public pure returns (string memory) {
return base(monkBeads("C7D2D4"));
}
/// @dev Accessory N°6 => Power Pole
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>',
'<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>',
'<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>',
'<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>'
)
)
);
}
/// @dev Accessory N°7 => Vintage Glasses
function item_7() public pure returns (string memory) {
return base(glasses("FC55FF", "DFA500", "0.31"));
}
/// @dev Accessory N°8 => Monk Beads Gold
function item_8() public pure returns (string memory) {
return base(monkBeads("FFDD00"));
}
/// @dev Accessory N°9 => Eye Patch
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>',
'<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>',
'<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>'
)
)
);
}
/// @dev Accessory N°10 => Sun Glasses
function item_10() public pure returns (string memory) {
return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1"));
}
/// @dev Accessory N°11 => Monk Beads Diamond
function item_11() public pure returns (string memory) {
return base(monkBeads("AAFFFD"));
}
/// @dev Accessory N°12 => Horns
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>'
)
)
);
}
/// @dev Accessory N°13 => Halo
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>'
)
)
);
}
/// @dev Accessory N°14 => Saiki Power
function item_14() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>',
'<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>',
'<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>',
'<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>',
'<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>',
'<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>',
'<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>',
'<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>',
abi.encodePacked(
'<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>',
'<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>',
'<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>',
'<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>',
'<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>',
'<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>'
)
)
)
);
}
/// @dev Accessory N°15 => No Face
function item_15() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>',
'<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>',
'<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>',
'<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>',
'<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>',
'<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>',
'<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>',
'<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>',
'<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>'
)
)
);
}
/// @dev Generate glasses with the given color and opacity
function glasses(
string memory color,
string memory stroke,
string memory opacity
) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<circle fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>',
'<circle fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>',
'<circle opacity="',
opacity,
'" fill="#',
color,
'" cx="161.5" cy="201.7" r="23.9"/>',
abi.encodePacked(
'<circle opacity="',
opacity,
'" fill="#',
color,
'" cx="232.9" cy="201.7" r="23.9"/>',
'<path fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>'
)
)
);
}
/// @dev Generate Monk Beads SVG with the given color
function monkBeads(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g fill="#',
color,
'" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>',
"</g>",
'<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>',
abi.encodePacked(
'<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">',
'<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>',
'<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>',
'<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>',
'<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>',
'<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>',
'<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>',
"</g>"
)
)
);
}
/// @notice Return the accessory name of the given id
/// @param id The accessory Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Glasses";
} else if (id == 3) {
name = "Bow Tie";
} else if (id == 4) {
name = "Monk Beads Classic";
} else if (id == 5) {
name = "Monk Beads Silver";
} else if (id == 6) {
name = "Power Pole";
} else if (id == 7) {
name = "Vintage Glasses";
} else if (id == 8) {
name = "Monk Beads Gold";
} else if (id == 9) {
name = "Eye Patch";
} else if (id == 10) {
name = "Sun Glasses";
} else if (id == 11) {
name = "Monk Beads Diamond";
} else if (id == 12) {
name = "Horns";
} else if (id == 13) {
name = "Halo";
} else if (id == 14) {
name = "Saiki Power";
} else if (id == 15) {
name = "No Face";
}
}
/// @dev The base SVG for the accessory
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Accessory">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Earrings SVG generator
library EarringsDetail {
/// @dev Earrings N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Earrings N°2 => Circle
function item_2() public pure returns (string memory) {
return base(circle("000000"));
}
/// @dev Earrings N°3 => Circle Silver
function item_3() public pure returns (string memory) {
return base(circle("C7D2D4"));
}
/// @dev Earrings N°4 => Ring
function item_4() public pure returns (string memory) {
return base(ring("000000"));
}
/// @dev Earrings N°5 => Circle Gold
function item_5() public pure returns (string memory) {
return base(circle("FFDD00"));
}
/// @dev Earrings N°6 => Ring Gold
function item_6() public pure returns (string memory) {
return base(ring("FFDD00"));
}
/// @dev Earrings N°7 => Heart
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>',
'<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>'
)
)
);
}
/// @dev Earrings N°8 => Gold
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>'
)
)
);
}
/// @dev Earrings N°9 => Circle Diamond
function item_9() public pure returns (string memory) {
return base(circle("AAFFFD"));
}
/// @dev Earrings N°10 => Drop Heart
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
drop(true),
'<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>',
drop(false),
'<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>'
)
)
);
}
/// @dev Earrings N11 => Ether
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>',
'<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>',
'<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>',
'<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>',
'<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>',
'<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>'
)
)
);
}
/// @dev Earrings N°12 => Drop Ether
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
drop(true),
'<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>',
'<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>',
'<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>',
drop(false),
'<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>',
'<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>',
'<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>'
)
)
);
}
/// @dev earring drop
function drop(bool right) private pure returns (string memory) {
return
string(
right
? abi.encodePacked(
'<circle cx="285.7" cy="243.2" r="3.4"/>',
'<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>'
)
: abi.encodePacked(
'<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>',
'<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>'
)
);
}
/// @dev Generate circle SVG with the given color
function circle(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<ellipse fill="#',
color,
'" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>',
'<ellipse fill="#',
color,
'" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>'
)
);
}
/// @dev Generate ring SVG with the given color
function ring(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="none" stroke="#',
color,
'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>',
'<path fill="none" stroke="#',
color,
'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>'
)
);
}
/// @notice Return the earring name of the given id
/// @param id The earring Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Circle";
} else if (id == 3) {
name = "Circle Silver";
} else if (id == 4) {
name = "Ring";
} else if (id == 5) {
name = "Circle Gold";
} else if (id == 6) {
name = "Ring Gold";
} else if (id == 7) {
name = "Heart";
} else if (id == 8) {
name = "Gold";
} else if (id == 9) {
name = "Circle Diamond";
} else if (id == 10) {
name = "Drop Heart";
} else if (id == 11) {
name = "Ether";
} else if (id == 12) {
name = "Drop Ether";
}
}
/// @dev The base SVG for the earrings
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Earrings">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Masks SVG generator
library MaskDetail {
/// @dev Mask N°1 => Maskless
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Mask N°2 => Classic
function item_2() public pure returns (string memory) {
return base(classicMask("575673"));
}
/// @dev Mask N°3 => Blue
function item_3() public pure returns (string memory) {
return base(classicMask(Colors.BLUE));
}
/// @dev Mask N°4 => Pink
function item_4() public pure returns (string memory) {
return base(classicMask(Colors.PINK));
}
/// @dev Mask N°5 => Black
function item_5() public pure returns (string memory) {
return base(classicMask(Colors.BLACK));
}
/// @dev Mask N°6 => Bandage White
function item_6() public pure returns (string memory) {
return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage())));
}
/// @dev Mask N°7 => Bandage Classic
function item_7() public pure returns (string memory) {
return base(string(abi.encodePacked(classicMask("575673"), bandage())));
}
/// @dev Mask N°8 => Nihon
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
classicMask("F5F5F5"),
'<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>'
)
)
);
}
/// @dev Generate classic mask SVG with the given color
function classicMask(string memory color) public pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="#',
color,
'" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>',
'<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>',
'<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>'
)
);
}
/// @dev Generate bandage SVG
function bandage() public pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>'
)
);
}
/// @notice Return the mask name of the given id
/// @param id The mask Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Maskless";
} else if (id == 2) {
name = "Classic";
} else if (id == 3) {
name = "Blue";
} else if (id == 4) {
name = "Pink";
} else if (id == 5) {
name = "Black";
} else if (id == 6) {
name = "Bandage White";
} else if (id == 7) {
name = "Bandage Classic";
} else if (id == 8) {
name = "Nihon";
}
}
/// @dev The base SVG for the eyes
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mask">', children, "</g>"));
}
}
// 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: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
/// @title Color constants
library Colors {
string internal constant BLACK = "33333D";
string internal constant BLACK_DEEP = "000000";
string internal constant BLUE = "7FBCFF";
string internal constant BROWN = "735742";
string internal constant GRAY = "7F8B8C";
string internal constant GREEN = "2FC47A";
string internal constant PINK = "FF78A9";
string internal constant PURPLE = "A839A4";
string internal constant RED = "D9005E";
string internal constant SAIKI = "F02AB6";
string internal constant WHITE = "F7F7F7";
string internal constant YELLOW = "EFED8F";
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
|
Mark N°13 => Ether
|
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>'
)
)
);
}
| 5,890,326 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
}
pragma solidity ^0.8.7;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication) external view returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
}
pragma solidity ^0.8.7;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
}
pragma solidity ^0.8.7;
/**
* @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);
}
}
pragma solidity ^0.8.7;
/**
* @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;
}
}
pragma solidity ^0.8.7;
/**
* @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);
}
}
pragma solidity ^0.8.7;
/**
* @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);
}
}
}
}
pragma solidity ^0.8.7;
/**
* @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);
}
pragma solidity ^0.8.7;
/**
* @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);
}
pragma solidity ^0.8.7;
/**
* @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;
}
}
pragma solidity ^0.8.7;
/**
* @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;
}
pragma solidity ^0.8.7;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.8.7;
/**
* @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);
}
pragma solidity ^0.8.7;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract");
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload));
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public {
// only internal transaction
require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge.");
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal;
function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal {
endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam);
}
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce];
require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message");
require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner {
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
pragma solidity ^0.8.7;
/**
* @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 ERC721B is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 private TotalToken = 0;
uint256 private MaxTokenId = 0;
uint256 internal immutable maxBatchSize;
uint256 private startIndex = 0;
uint256 private endIndex = 0;
address private burnaddress = 0x000000000000000000000000000000000000dEaD;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `TotalToken_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 startIndex_,
uint256 endIndex_
) {
require(maxBatchSize_ > 0, "ERC721B: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
currentIndex = startIndex_;
startIndex = startIndex_;
endIndex = endIndex_;
MaxTokenId = endIndex_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return TotalToken;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index <= MaxTokenId, "ERC721B: global index out of bounds");
uint256 tokenIdsIdx = 0;
for (uint256 i = 0; i <= MaxTokenId; i++) {
TokenOwnership memory ownership = _ownerships[i];
if(_inrange(i)){
if ( (ownership.addr != burnaddress) && (i < currentIndex)) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
else
{
if ((ownership.addr != address(0)) && (ownership.addr != burnaddress)) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert("ERC721A: unable to get token by index");
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(TotalToken). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i <= MaxTokenId; i++) {
TokenOwnership memory ownership = _ownerships[i];
if(_inrange(i) && (i < currentIndex)){
if ((ownership.addr != address(0))) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
else
{
if (ownership.addr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721B: balance query for the zero address");
require(owner != burnaddress, "ERC721B: balance query for the burnaddress");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
require(
owner != burnaddress,
"ERC721A: number minted query for the burnaddress"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721B: owner query for nonexistent token");
//If it is airdrop(transfered between chains), we have owner address set already.
TokenOwnership memory ownership = _ownerships[tokenId];
if ( !_inrange(tokenId) ) {
if ( (ownership.addr != address(0)) && (ownership.addr != burnaddress) )
return ownership;
else
revert("ERC721B: unable to determine the owner of token");
}
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
if (lowestTokenToCheck < startIndex) {
lowestTokenToCheck = startIndex;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
ownership = _ownerships[curr];
if ((ownership.addr != address(0)) && (ownership.addr != burnaddress) ) {
return ownership;
}
}
revert("ERC721B: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721B.ownerOf(tokenId);
require(to != owner, "ERC721B: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721B: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721B: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721B: 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 {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721B: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
//@dan token could be out of range from tranferring between blockchains
if (_inrange(tokenId))
{
return ((tokenId < currentIndex) && (_ownerships[tokenId].addr !=burnaddress));
}
else
{
return ((_ownerships[tokenId].addr != address(0)) && (_ownerships[tokenId].addr !=burnaddress));
}
}
/**
* @dev Returns whether `tokenId` in start and end ranges.
*
* Tokens can be out of range by airdrop.
*/
function _inrange(uint256 tokenId) internal view returns (bool) {
//@dan token could be out of range from tranferring between blockchains
return ((tokenId >= startIndex) && (tokenId <= endIndex));
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721B: mint to the zero address");
require(to != burnaddress, "ERC721B: mint to the burn address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721B: token already minted");
require(quantity <= maxBatchSize, "ERC721B: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
TotalToken++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Safely airdrop `tokenId` and transfers it to `to`. This is for the receive side of Level Zero Chain transfer
*
* 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 _airdrop(address to, uint256 tokenId) internal virtual {
_airdrop(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 _airdrop(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_airdropbyId(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 _airdropbyId(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(to != burnaddress, "ERC721B: mint to the burn address");
_beforeTokenTransfers(address(0), to, tokenId, 1);
TotalToken++;
if(tokenId > MaxTokenId){
MaxTokenId = tokenId;
}
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + 1,
addressData.numberMinted + 1);
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
emit Transfer(address(0), to, tokenId);
}
/**
* @dev ERC721A uses address(0), so we use 0x000000000000000000000000000000000000dEaD as burn address
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
address owner = ERC721B.ownerOf(tokenId);
_beforeTokenTransfers(owner, burnaddress, tokenId, 1);
// Clear approvals
_approve(address(0), tokenId, owner);
AddressData memory addressData = _addressData[owner];
_addressData[owner] = AddressData(
addressData.balance - 1,
addressData.numberMinted - 1);
TotalToken--;
_ownerships[tokenId] = TokenOwnership(burnaddress, uint64(block.timestamp));
//@dan only do this if minted in range.
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_inrange(nextTokenId) && (_ownerships[nextTokenId].addr == address(0))) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721B: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721B: transfer from incorrect owner"
);
require(to != address(0), "ERC721B: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
//@dan only do this if minted in range.
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_inrange(nextTokenId) && (_ownerships[nextTokenId].addr == address(0))) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721B: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
pragma solidity ^0.8.7;
interface IGOKU {
function burn(address _from, uint256 _amount) external;
}
contract GokudoParadiseContract is Ownable, ERC721B, NonblockingReceiver {
string private baseURI;
uint256 public MAX_MINT_ETHEREUM;
uint256 public Mintprice = 29000000000000000;
uint256 constant public UPGRADE_PRICE = 5000 ether;
uint public MaxPatchPerTx;
bool public bSalesStart = false;
bool public bUpgradeIsActive = false;
uint gasForDestinationLzReceive = 350000;
mapping(uint16 => address) private _TopEXAddress;
mapping(uint => uint256) public upgradenewtokenid;
event InternaltokenidChange(address _by, uint _tokenId, uint256 _internaltokenID);
IGOKU public GOKU;
constructor(
uint256 maxBatchSize_,
uint256 startIndex_,
uint256 endIndex_,
address _layerZeroEndpoint
) ERC721B("Gokudo Paradise", "GokudoParadise", maxBatchSize_, startIndex_, endIndex_) {
MaxPatchPerTx = maxBatchSize_;
MAX_MINT_ETHEREUM = endIndex_ + 1;
endpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
// Use top exchange addresses to seed random number. Changes every second
_TopEXAddress[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
_TopEXAddress[1] = 0xDA9dfA130Df4dE4673b89022EE50ff26f6EA73Cf;
_TopEXAddress[2] = 0x6262998Ced04146fA42253a5C0AF90CA02dfd2A3;
_TopEXAddress[3] = 0xA7EFAe728D2936e78BDA97dc267687568dD593f3;
_TopEXAddress[4] = 0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8;
}
function setMaxMintNum(uint _MAX_MINT) external onlyOwner {
MAX_MINT_ETHEREUM = _MAX_MINT;
}
function setMintprice(uint _Mintprice) external onlyOwner {
Mintprice = _Mintprice;
}
function flipSalesStart() public onlyOwner {
bSalesStart = !bSalesStart;
}
function flipUpgradeIsActive() public onlyOwner {
bUpgradeIsActive = !bUpgradeIsActive;
}
// mint function
function mint(uint8 numTokens) external payable {
require(bSalesStart, "Sale is not started");
require(totalSupply() + numTokens <= MAX_MINT_ETHEREUM, "Can not mint more than MAX_MINT_ETHEREUM");
require(numTokens > 0 && numTokens <= MaxPatchPerTx, "Can not mint more than MaxPatchPerTx");
require(msg.value >= Mintprice*numTokens, "Not paid enough ETH.");
_safeMint(msg.sender, numTokens);
}
function MintByOwner(address _to,uint256 mintamount) external onlyOwner {
require(totalSupply() + mintamount <= MAX_MINT_ETHEREUM, "Can not mint more than MAX_MINT_ETHEREUM");
_safeMint(_to, mintamount);
}
// This function transfers the nft from your address on the
// source chain to the same address on the destination chain
function traverseChains(uint16 _chainId, uint tokenId) public payable {
require(msg.sender == ownerOf(tokenId), "You must own the token to traverse");
require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel");
// burn NFT, eliminating it from circulation on src chain
_burn(tokenId);
// abi.encode() the payload with the values to send
bytes memory payload = abi.encode(msg.sender, tokenId);
// encode adapterParams to specify more gas for the destination
uint16 version = 1;
bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
// get the fees we need to pay to LayerZero + Relayer to cover message delivery
// you will be refunded for extra gas paid
(uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams);
require(msg.value >= messageFee, "Msg.value not enough to cover messageFee. Send gas for message fees");
endpoint.send{value: msg.value}(
_chainId, // destination chainId
trustedRemoteLookup[_chainId], // destination address of nft contract
payload, // abi.encoded()'ed bytes
payable(msg.sender), // refund address
address(0x0), // 'zroPaymentAddress' unused for this
adapterParams // txParameters
);
}
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
function getupgradedtokenID(uint _tokenId) public view returns( uint256 ){
return upgradenewtokenid[_tokenId];
}
// This allows the devs to receive kind donations
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
address address1= 0xe7B39710e2b1c7027Ba2870B4a1ADfee3Cf44992;
address address2= 0x153aaDE21B072169Ffab664d88192dA3d0F0Ff64;
payable(address1).transfer(balance*4/10);
payable(address2).transfer(balance*6/10);
}
// just in case this fixed variable limits us from future integrations
function setGasForDestinationLzReceive(uint newVal) external onlyOwner {
gasForDestinationLzReceive = newVal;
}
function setGOKUTokenaddress(address _GOKUToken) external onlyOwner {
GOKU= IGOKU(_GOKUToken);
}
function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function getSomeRandomNumber(uint _seed, uint _limit) internal view returns (uint16) {
uint extra = 0;
for (uint16 i = 0; i < 5; i++) {
extra += _TopEXAddress[i].balance;
}
uint random = uint(
keccak256(
abi.encodePacked(
_seed,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender,
totalSupply(),
extra
)
)
);
return uint16(random % _limit);
}
//Use random number to upgrade traits. This is for future use only, not used at mint.
function upgrade(address owner, uint256 tokenId) public returns (bool) {
require(bUpgradeIsActive, "Compose is not active at the moment");
require(ERC721B.ownerOf(tokenId) == owner, "You do not have this token");
GOKU.burn(msg.sender, UPGRADE_PRICE);
uint256 newtokenId = getSomeRandomNumber(tokenId, 9999);
upgradenewtokenid[tokenId] = newtokenId;
emit InternaltokenidChange(msg.sender, tokenId, newtokenId);
return true;
}
// ------------------
// Internal Functions
// ------------------
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
// decode
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
// mint the tokens back into existence on destination chain
_airdrop(toAddr, tokenId);
}
function _baseURI() override internal view returns (string memory) {
return baseURI;
}
}
|
Safely airdrop `tokenId` and transfers it to `to`. This is for the receive side of Level Zero Chain transfer 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 _airdrop(address to, uint256 tokenId) internal virtual {
_airdrop(to, tokenId, "");
}
| 1,228,106 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
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);
}
library Math {
/**
* @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);
}
}
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;
}
}
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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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);
}
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");
}
}
}
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
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");
}
}
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract DInterest is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
// Constants
uint256 internal constant PRECISION = 10**18;
uint256 internal constant ONE = 10**18;
// User deposit data
// Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1
struct Deposit {
uint256 amount; // Amount of stablecoin deposited
uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint256 interestOwed; // Deficit incurred to the pool at time of deposit
uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit
bool active; // True if not yet withdrawn, false if withdrawn
bool finalSurplusIsNegative;
uint256 finalSurplusAmount; // Surplus remaining after withdrawal
uint256 mintMPHAmount; // Amount of MPH minted to user
}
Deposit[] internal deposits;
uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded
uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount whose deficit hasn't been funded
// Funding data
// Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1
struct Funding {
// deposits with fromDepositID < ID <= toDepositID are funded
uint256 fromDepositID;
uint256 toDepositID;
uint256 recordedFundedDepositAmount;
uint256 recordedMoneyMarketIncomeIndex;
}
Funding[] internal fundingList;
// Params
uint256 public MinDepositPeriod; // Minimum deposit period, in seconds
uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds
uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins
uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins
// Instance variables
uint256 public totalDeposit;
uint256 public totalInterestOwed;
// External smart contracts
IMoneyMarket public moneyMarket;
ERC20 public stablecoin;
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
NFT public fundingNFT;
MPHMinter public mphMinter;
// Events
event EDeposit(
address indexed sender,
uint256 indexed depositID,
uint256 amount,
uint256 maturationTimestamp,
uint256 interestAmount,
uint256 mintMPHAmount
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
uint256 indexed fundingID,
bool early,
uint256 takeBackMPHAmount
);
event EFund(
address indexed sender,
uint256 indexed fundingID,
uint256 deficitAmount,
uint256 mintMPHAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
struct DepositLimit {
uint256 MinDepositPeriod;
uint256 MaxDepositPeriod;
uint256 MinDepositAmount;
uint256 MaxDepositAmount;
}
constructor(
DepositLimit memory _depositLimit,
address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract)
address _stablecoin, // Address of the stablecoin used to store funds
address _feeModel, // Address of the FeeModel contract that determines how fees are charged
address _interestModel, // Address of the InterestModel contract that determines how much interest to offer
address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate
address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract)
address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract)
address _mphMinter // Address of the contract for handling minting MPH to users
) public {
// Verify input addresses
require(
_moneyMarket.isContract() &&
_stablecoin.isContract() &&
_feeModel.isContract() &&
_interestModel.isContract() &&
_interestOracle.isContract() &&
_depositNFT.isContract() &&
_fundingNFT.isContract() &&
_mphMinter.isContract(),
"DInterest: An input address is not a contract"
);
moneyMarket = IMoneyMarket(_moneyMarket);
stablecoin = ERC20(_stablecoin);
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingNFT = NFT(_fundingNFT);
mphMinter = MPHMinter(_mphMinter);
// Ensure moneyMarket uses the same stablecoin
require(
moneyMarket.stablecoin() == _stablecoin,
"DInterest: moneyMarket.stablecoin() != _stablecoin"
);
// Ensure interestOracle uses the same moneyMarket
require(
interestOracle.moneyMarket() == _moneyMarket,
"DInterest: interestOracle.moneyMarket() != _moneyMarket"
);
// Verify input uint256 parameters
require(
_depositLimit.MaxDepositPeriod > 0 &&
_depositLimit.MaxDepositAmount > 0,
"DInterest: An input uint256 is 0"
);
require(
_depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod,
"DInterest: Invalid DepositPeriod range"
);
require(
_depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount,
"DInterest: Invalid DepositAmount range"
);
MinDepositPeriod = _depositLimit.MinDepositPeriod;
MaxDepositPeriod = _depositLimit.MaxDepositPeriod;
MinDepositAmount = _depositLimit.MinDepositAmount;
MaxDepositAmount = _depositLimit.MaxDepositAmount;
totalDeposit = 0;
}
/**
Public actions
*/
function deposit(uint256 amount, uint256 maturationTimestamp)
external
nonReentrant
{
_deposit(amount, maturationTimestamp);
}
function withdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, false);
}
function earlyWithdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, true);
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
/**
Deficit funding
*/
function fundAll() external nonReentrant {
// Calculate current deficit
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex
})
);
// Update relevant values
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositToFund = 0;
// Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
// Deposit still active, use current surplus
(isNegative, surplus) = surplusOfDeposit(id);
} else {
// Deposit has been withdrawn, use recorded final surplus
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
// Add on deficit to total
totalDeficit = totalDeficit.add(surplus);
} else {
// Has surplus
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositToFund = totalDepositToFund.add(
depositEntry.amount
);
}
}
if (totalSurplus >= totalDeficit) {
// Deposits selected have a surplus as a whole, revert
revert("DInterest: Selected deposits in surplus");
} else {
// Deduct surplus from totalDeficit
totalDeficit = totalDeficit.sub(totalSurplus);
}
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositToFund,
recordedMoneyMarketIncomeIndex: incomeIndex
})
);
// Update relevant values
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositToFund
);
_fund(totalDeficit);
}
/**
Public getters
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) = interestOracle
.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed = totalDeposit.add(totalInterestOwed);
if (totalValue >= totalOwed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue = depositEntry
.amount
.mul(currentMoneyMarketIncomeIndex)
.div(depositEntry.initialMoneyMarketIncomeIndex);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
function depositIsFunded(uint256 id) public view returns (bool) {
return (id <= latestFundedDepositID);
}
function depositsLength() external view returns (uint256) {
return deposits.length;
}
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
function getDeposit(uint256 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID.sub(1)];
}
function getFunding(uint256 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID.sub(1)];
}
function moneyMarketIncomeIndex() external returns (uint256) {
return moneyMarket.incomeIndex();
}
/**
Param setters
*/
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestOracle = IInterestOracle(newValue);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
moneyMarket.setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMinDepositPeriod(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositPeriod, "DInterest: invalid value");
MinDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue);
}
function setMaxDepositPeriod(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositPeriod && newValue > 0,
"DInterest: invalid value"
);
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue);
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositAmount, "DInterest: invalid value");
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setMaxDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MaxDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue);
}
function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
depositNFT.setTokenURI(tokenId, newURI);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
fundingNFT.setTokenURI(tokenId, newURI);
}
function setFundingNFTBaseURI(string calldata newURI) external onlyOwner {
fundingNFT.setBaseURI(newURI);
}
function setFundingNFTContractURI(string calldata newURI)
external
onlyOwner
{
fundingNFT.setContractURI(newURI);
}
/**
Internal getters
*/
function _getDeposit(uint256 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID.sub(1)];
}
function _getFunding(uint256 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID.sub(1)];
}
/**
Internals
*/
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
// Cannot deposit 0
require(amount > 0, "DInterest: Deposit amount is 0");
// Ensure deposit amount is not more than maximum
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
// Ensure deposit period is at least MinDepositPeriod
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
// Update totalDeposit
totalDeposit = totalDeposit.add(amount);
// Update funding related data
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount);
// Calculate interest
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.add(interestAmount);
// Mint MPH for msg.sender
uint256 mintMPHAmount = mphMinter.mintDepositorReward(
msg.sender,
interestAmount
);
// Record deposit data for `msg.sender`
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount
})
);
// Transfer `amount` stablecoin to DInterest
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Lend `amount` stablecoin to money market
stablecoin.safeIncreaseAllowance(address(moneyMarket), amount);
moneyMarket.deposit(amount);
// Mint depositNFT
depositNFT.mint(msg.sender, id);
// Emit event
emit EDeposit(
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
// Verify deposit is active and set to inactive
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
// Verify `now < depositEntry.maturationTimestamp`
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
} else {
// Verify `now >= depositEntry.maturationTimestamp`
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
// Verify msg.sender owns the depositNFT
require(
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
// Take back MPH
uint256 takeBackMPHAmount = mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
// Update totalDeposit
totalDeposit = totalDeposit.sub(depositEntry.amount);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed);
// Burn depositNFT
depositNFT.burn(depositID);
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
// Withdraw the principal of the deposit from money market
withdrawAmount = depositEntry.amount;
} else {
// Withdraw the principal & the interest from money market
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(depositEntry.interestOwed);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
(bool depositIsNegative, uint256 depositSurplus) = surplusOfDeposit(
depositID
);
// If deposit was funded, payout interest to funder
if (depositIsFunded(depositID)) {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
uint256 interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositEntry.amount
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
// Send interest to funder
uint256 transferToFunderAmount = (early && depositIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
stablecoin.safeTransfer(
fundingNFT.ownerOf(fundingID),
transferToFunderAmount
);
}
} else {
// Remove deposit from future deficit fundings
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount
);
// Record remaining surplus
depositEntry.finalSurplusIsNegative = depositIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
// Send `withdrawAmount - feeAmount` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount));
// Send `feeAmount` stablecoin to feeModel beneficiary
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
// Emit event
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
function _fund(uint256 totalDeficit) internal {
// Transfer `totalDeficit` stablecoins from msg.sender
stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit);
// Deposit `totalDeficit` stablecoins into moneyMarket
stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit);
moneyMarket.deposit(totalDeficit);
// Mint fundingNFT
fundingNFT.mint(msg.sender, fundingList.length);
// Mint MPH for msg.sender
uint256 mintMPHAmount = mphMinter.mintFunderReward(
msg.sender,
totalDeficit
);
// Emit event
uint256 fundingID = fundingList.length;
emit EFund(msg.sender, fundingID, totalDeficit, mintMPHAmount);
}
}
library DecMath {
using SafeMath for uint256;
uint256 internal constant PRECISION = 10**18;
function decmul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISION);
}
function decdiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISION).div(b);
}
}
contract ComptrollerMock {
uint256 public constant CLAIM_AMOUNT = 10**18;
ERC20Mock public comp;
constructor (address _comp) public {
comp = ERC20Mock(_comp);
}
function claimComp(address holder) external {
comp.mint(holder, CLAIM_AMOUNT);
}
function getCompAddress() external view returns (address) {
return address(comp);
}
}
contract LendingPoolAddressesProviderMock {
address internal pool;
address internal core;
function getLendingPool() external view returns (address) {
return pool;
}
function setLendingPoolImpl(address _pool) external {
pool = _pool;
}
function getLendingPoolCore() external view returns (address) {
return core;
}
function setLendingPoolCoreImpl(address _pool) external {
core = _pool;
}
}
contract LendingPoolCoreMock {
LendingPoolMock internal lendingPool;
function setLendingPool(address lendingPoolAddress) public {
lendingPool = LendingPoolMock(lendingPoolAddress);
}
function bounceTransfer(address _reserve, address _sender, uint256 _amount)
external
{
ERC20 token = ERC20(_reserve);
token.transferFrom(_sender, address(this), _amount);
token.transfer(msg.sender, _amount);
}
// The equivalent of exchangeRateStored() for Compound cTokens
function getReserveNormalizedIncome(address _reserve) external view returns (uint256) {
(, , , , , , , , , , , address aTokenAddress, ) = lendingPool
.getReserveData(_reserve);
ATokenMock aToken = ATokenMock(aTokenAddress);
return aToken.normalizedIncome();
}
}
contract LendingPoolMock {
mapping(address => address) internal reserveAToken;
LendingPoolCoreMock public core;
constructor(address _core) public {
core = LendingPoolCoreMock(_core);
}
function setReserveAToken(address _reserve, address _aTokenAddress) external {
reserveAToken[_reserve] = _aTokenAddress;
}
function deposit(address _reserve, uint256 _amount, uint16)
external
{
ERC20 token = ERC20(_reserve);
core.bounceTransfer(_reserve, msg.sender, _amount);
// Mint aTokens
address aTokenAddress = reserveAToken[_reserve];
ATokenMock aToken = ATokenMock(aTokenAddress);
aToken.mint(msg.sender, _amount);
token.transfer(aTokenAddress, _amount);
}
function getReserveData(address _reserve)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256 liquidityRate,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
address aTokenAddress,
uint40
)
{
aTokenAddress = reserveAToken[_reserve];
ATokenMock aToken = ATokenMock(aTokenAddress);
liquidityRate = aToken.liquidityRate();
}
}
interface IFeeModel {
function beneficiary() external view returns (address payable);
function getFee(uint256 _txAmount)
external
pure
returns (uint256 _feeAmount);
}
contract PercentageFeeModel is IFeeModel {
using SafeMath for uint256;
address payable public beneficiary;
constructor(address payable _beneficiary) public {
beneficiary = _beneficiary;
}
function getFee(uint256 _txAmount)
external
pure
returns (uint256 _feeAmount)
{
_feeAmount = _txAmount.div(10); // Precision is decreased by 1 decimal place
}
}
interface IInterestOracle {
function updateAndQuery() external returns (bool updated, uint256 value);
function query() external view returns (uint256 value);
function moneyMarket() external view returns (address);
}
interface IInterestModel {
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 moneyMarketInterestRatePerSecond,
bool surplusIsNegative,
uint256 surplusAmount
) external view returns (uint256 interestAmount);
}
contract LinearInterestModel {
using SafeMath for uint256;
using DecMath for uint256;
uint256 public constant PRECISION = 10**18;
uint256 public IRMultiplier;
constructor(uint256 _IRMultiplier) public {
IRMultiplier = _IRMultiplier;
}
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 moneyMarketInterestRatePerSecond,
bool, /*surplusIsNegative*/
uint256 /*surplusAmount*/
) external view returns (uint256 interestAmount) {
// interestAmount = depositAmount * moneyMarketInterestRatePerSecond * IRMultiplier * depositPeriodInSeconds
interestAmount = depositAmount
.mul(PRECISION)
.decmul(moneyMarketInterestRatePerSecond)
.decmul(IRMultiplier)
.mul(depositPeriodInSeconds)
.div(PRECISION);
}
}
interface IMoneyMarket {
function deposit(uint256 amount) external;
function withdraw(uint256 amountInUnderlying)
external
returns (uint256 actualAmountWithdrawn);
function claimRewards() external; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool
function totalValue() external returns (uint256); // The total value locked in the money market, in terms of the underlying stablecoin
function incomeIndex() external returns (uint256); // Used for calculating the interest generated (e.g. cDai's price for the Compound market)
function stablecoin() external view returns (address);
function setRewards(address newValue) external;
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
}
contract AaveMarket is IMoneyMarket, Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint16 internal constant REFERRALCODE = 20; // Aave referral program code
ILendingPoolAddressesProvider public provider; // Used for fetching the current address of LendingPool
ERC20 public stablecoin;
constructor(address _provider, address _stablecoin) public {
// Verify input addresses
require(
_provider != address(0) && _stablecoin != address(0),
"AaveMarket: An input address is 0"
);
require(
_provider.isContract() && _stablecoin.isContract(),
"AaveMarket: An input address is not a contract"
);
provider = ILendingPoolAddressesProvider(_provider);
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "AaveMarket: amount is 0");
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
address lendingPoolCore = provider.getLendingPoolCore();
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Approve `amount` stablecoin to lendingPool
stablecoin.safeIncreaseAllowance(lendingPoolCore, amount);
// Deposit `amount` stablecoin to lendingPool
lendingPool.deposit(address(stablecoin), amount, REFERRALCODE);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(amountInUnderlying > 0, "AaveMarket: amountInUnderlying is 0");
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
// Initialize aToken
(, , , , , , , , , , , address aTokenAddress, ) = lendingPool
.getReserveData(address(stablecoin));
IAToken aToken = IAToken(aTokenAddress);
// Redeem `amountInUnderlying` aToken, since 1 aToken = 1 stablecoin
aToken.redeem(amountInUnderlying);
// Transfer `amountInUnderlying` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, amountInUnderlying);
return amountInUnderlying;
}
function claimRewards() external {}
function totalValue() external returns (uint256) {
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
// Initialize aToken
(, , , , , , , , , , , address aTokenAddress, ) = lendingPool
.getReserveData(address(stablecoin));
IAToken aToken = IAToken(aTokenAddress);
return aToken.balanceOf(address(this));
}
function incomeIndex() external returns (uint256) {
ILendingPoolCore lendingPoolCore = ILendingPoolCore(
provider.getLendingPoolCore()
);
return lendingPoolCore.getReserveNormalizedIncome(address(stablecoin));
}
function setRewards(address newValue) external {}
}
interface IAToken {
function redeem(uint256 _amount) external;
function balanceOf(address owner) external view returns (uint256);
}
interface ILendingPool {
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external;
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
);
}
interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address _pool) external;
function getLendingPoolCore() external view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) external;
function getLendingPoolDataProvider() external view returns (address);
function setLendingPoolDataProviderImpl(address _provider) external;
function getLendingPoolParametersProvider() external view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider)
external;
function getTokenDistributor() external view returns (address);
function setTokenDistributor(address _tokenDistributor) external;
function getFeeProvider() external view returns (address);
function setFeeProviderImpl(address _feeProvider) external;
function getLendingPoolLiquidationManager() external view returns (address);
function setLendingPoolLiquidationManager(address _manager) external;
function getLendingPoolManager() external view returns (address);
function setLendingPoolManager(address _lendingPoolManager) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address _priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address _lendingRateOracle) external;
}
interface ILendingPoolCore {
// The equivalent of exchangeRateStored() for Compound cTokens
function getReserveNormalizedIncome(address _reserve)
external
view
returns (uint256);
}
contract CompoundERC20Market is IMoneyMarket, Ownable {
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint256 internal constant ERRCODE_OK = 0;
ICERC20 public cToken;
IComptroller public comptroller;
address public rewards;
ERC20 public stablecoin;
constructor(
address _cToken,
address _comptroller,
address _rewards,
address _stablecoin
) public {
// Verify input addresses
require(
_cToken != address(0) &&
_comptroller != address(0) &&
_rewards != address(0) &&
_stablecoin != address(0),
"CompoundERC20Market: An input address is 0"
);
require(
_cToken.isContract() &&
_comptroller.isContract() &&
_rewards.isContract() &&
_stablecoin.isContract(),
"CompoundERC20Market: An input address is not a contract"
);
cToken = ICERC20(_cToken);
comptroller = IComptroller(_comptroller);
rewards = _rewards;
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "CompoundERC20Market: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Deposit `amount` stablecoin into cToken
stablecoin.safeIncreaseAllowance(address(cToken), amount);
require(
cToken.mint(amount) == ERRCODE_OK,
"CompoundERC20Market: Failed to mint cTokens"
);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"CompoundERC20Market: amountInUnderlying is 0"
);
// Withdraw `amountInUnderlying` stablecoin from cToken
require(
cToken.redeemUnderlying(amountInUnderlying) == ERRCODE_OK,
"CompoundERC20Market: Failed to redeem"
);
// Transfer `amountInUnderlying` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, amountInUnderlying);
return amountInUnderlying;
}
function claimRewards() external {
comptroller.claimComp(address(this));
ERC20 comp = ERC20(comptroller.getCompAddress());
comp.safeTransfer(rewards, comp.balanceOf(address(this)));
}
function totalValue() external returns (uint256) {
uint256 cTokenBalance = cToken.balanceOf(address(this));
// Amount of stablecoin units that 1 unit of cToken can be exchanged for, scaled by 10^18
uint256 cTokenPrice = cToken.exchangeRateCurrent();
return cTokenBalance.decmul(cTokenPrice);
}
function incomeIndex() external returns (uint256) {
return cToken.exchangeRateCurrent();
}
/**
Param setters
*/
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "CompoundERC20Market: not contract");
rewards = newValue;
emit ESetParamAddress(msg.sender, "rewards", newValue);
}
}
interface ICERC20 {
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)
external
view
returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function seize(address liquidator, address borrower, uint256 seizeTokens)
external
returns (uint256);
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,
address cTokenCollateral
) external returns (uint256);
}
interface IComptroller {
function claimComp(address holder) external;
function getCompAddress() external view returns (address);
}
contract YVaultMarket is IMoneyMarket, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
Vault public vault;
ERC20 public stablecoin;
constructor(address _vault, address _stablecoin) public {
// Verify input addresses
require(
_vault != address(0) && _stablecoin != address(0),
"YVaultMarket: An input address is 0"
);
require(
_vault.isContract() && _stablecoin.isContract(),
"YVaultMarket: An input address is not a contract"
);
vault = Vault(_vault);
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "YVaultMarket: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Approve `amount` stablecoin to vault
stablecoin.safeIncreaseAllowance(address(vault), amount);
// Deposit `amount` stablecoin to vault
vault.deposit(amount);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"YVaultMarket: amountInUnderlying is 0"
);
// Withdraw `amountInShares` shares from vault
uint256 sharePrice = vault.getPricePerFullShare();
uint256 amountInShares = amountInUnderlying.decdiv(sharePrice);
vault.withdraw(amountInShares);
// Transfer stablecoin to `msg.sender`
actualAmountWithdrawn = stablecoin.balanceOf(address(this));
stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn);
}
function claimRewards() external {}
function totalValue() external returns (uint256) {
uint256 sharePrice = vault.getPricePerFullShare();
uint256 shareBalance = vault.balanceOf(address(this));
return shareBalance.decmul(sharePrice);
}
function incomeIndex() external returns (uint256) {
return vault.getPricePerFullShare();
}
function setRewards(address newValue) external {}
}
interface Vault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
/**
* @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
);
}
interface IRewards {
function notifyRewardAmount(uint256 reward) external;
}
contract MPHMinter is Ownable {
using Address for address;
using DecMath for uint256;
using SafeMath for uint256;
uint256 internal constant PRECISION = 10**18;
/**
@notice The multiplier applied to the interest generated by a pool when minting MPH
*/
mapping(address => uint256) public poolMintingMultiplier;
/**
@notice The multiplier applied to the interest generated by a pool when letting depositors keep MPH
*/
mapping(address => uint256) public poolDepositorRewardMultiplier;
/**
@notice The multiplier applied to the interest generated by a pool when letting deficit funders keep MPH
*/
mapping(address => uint256) public poolFunderRewardMultiplier;
/**
@notice Multiplier used for calculating dev reward
*/
uint256 public devRewardMultiplier;
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
/**
External contracts
*/
MPHToken public mph;
address public govTreasury;
address public devWallet;
constructor(
address _mph,
address _govTreasury,
address _devWallet,
uint256 _devRewardMultiplier
) public {
mph = MPHToken(_mph);
govTreasury = _govTreasury;
devWallet = _devWallet;
devRewardMultiplier = _devRewardMultiplier;
}
function mintDepositorReward(address to, uint256 interestAmount)
external
returns (uint256)
{
uint256 multiplier = poolMintingMultiplier[msg.sender];
uint256 mintAmount = interestAmount.decmul(multiplier);
if (mintAmount == 0) {
// sender is not a pool/has been deactivated
return 0;
}
mph.ownerMint(to, mintAmount);
mph.ownerMint(devWallet, mintAmount.decmul(devRewardMultiplier));
return mintAmount;
}
function mintFunderReward(address to, uint256 interestAmount)
external
returns (uint256)
{
uint256 multiplier = poolMintingMultiplier[msg.sender].decmul(
poolFunderRewardMultiplier[msg.sender]
);
uint256 mintAmount = interestAmount.decmul(multiplier);
if (mintAmount == 0) {
// sender is not a pool/has been deactivated
return 0;
}
mph.ownerMint(to, mintAmount);
mph.ownerMint(devWallet, mintAmount.decmul(devRewardMultiplier));
return mintAmount;
}
function takeBackDepositorReward(
address from,
uint256 mintMPHAmount,
bool early
) external returns (uint256) {
uint256 takeBackAmount = early
? mintMPHAmount
: mintMPHAmount.decmul(
PRECISION.sub(poolDepositorRewardMultiplier[msg.sender])
);
if (takeBackAmount == 0) {
// sender is not a pool/has been deactivated
return 0;
}
mph.ownerTransfer(from, govTreasury, takeBackAmount);
return takeBackAmount;
}
/**
Param setters
*/
function setGovTreasury(address newValue) external onlyOwner {
require(newValue != address(0), "MPHMinter: 0 address");
govTreasury = newValue;
emit ESetParamAddress(msg.sender, "govTreasury", newValue);
}
function setDevWallet(address newValue) external onlyOwner {
require(newValue != address(0), "MPHMinter: 0 address");
devWallet = newValue;
emit ESetParamAddress(msg.sender, "devWallet", newValue);
}
function setPoolMintingMultiplier(address pool, uint256 newMultiplier)
external
onlyOwner
{
require(pool.isContract(), "MPHMinter: pool not contract");
poolMintingMultiplier[pool] = newMultiplier;
emit ESetParamUint(msg.sender, "poolMintingMultiplier", newMultiplier);
}
function setPoolDepositorRewardMultiplier(
address pool,
uint256 newMultiplier
) external onlyOwner {
require(pool.isContract(), "MPHMinter: pool not contract");
require(newMultiplier <= PRECISION, "MPHMinter: invalid multiplier");
poolDepositorRewardMultiplier[pool] = newMultiplier;
emit ESetParamUint(
msg.sender,
"poolDepositorRewardMultiplier",
newMultiplier
);
}
function setPoolFunderRewardMultiplier(address pool, uint256 newMultiplier)
external
onlyOwner
{
require(pool.isContract(), "MPHMinter: pool not contract");
poolFunderRewardMultiplier[pool] = newMultiplier;
emit ESetParamUint(
msg.sender,
"poolFunderRewardMultiplier",
newMultiplier
);
}
}
interface OneSplitAudit {
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
) external payable returns (uint256 returnAmount);
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns (uint256 returnAmount, uint256[] memory distribution);
}
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(
_msgSender() == rewardDistribution,
"Caller is not reward distribution"
);
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakeToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _stakeToken) public {
stakeToken = IERC20(_stakeToken);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
}
}
contract Rewards is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public rewardToken;
OneSplitAudit public oneSplit;
uint256 public constant DURATION = 7 days;
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
bool public initialized = false;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier checkStart {
require(block.timestamp >= starttime, "Rewards: not start");
_;
}
constructor(
address _stakeToken,
address _rewardToken,
address _oneSplit,
uint256 _starttime
) public LPTokenWrapper(_stakeToken) {
rewardToken = IERC20(_rewardToken);
oneSplit = OneSplitAudit(_oneSplit);
starttime = _starttime;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Rewards: cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
updateReward(msg.sender)
checkStart
{
require(amount > 0, "Rewards: cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
_notifyRewardAmount(reward);
}
function dump(address token, uint256 parts) external {
require(token != address(stakeToken), "Rewards: no dump stakeToken");
require(token != address(rewardToken), "Rewards: no dump rewardToken");
// dump token for rewardToken
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
(uint256 returnAmount, uint256[] memory distribution) = oneSplit
.getExpectedReturn(
token,
address(rewardToken),
tokenBalance,
parts,
0
);
uint256 receivedRewardTokenAmount = oneSplit.swap(
token,
address(rewardToken),
tokenBalance,
returnAmount,
distribution,
0
);
// notify reward
_notifyRewardAmount(receivedRewardTokenAmount);
}
function _notifyRewardAmount(uint256 reward) internal {
// https://sips.synthetix.io/sips/sip-77
require(
reward < uint256(-1) / 10**18,
"Rewards: rewards too large, would lock"
);
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
}
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev 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;
}
/**
* @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 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 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 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 {
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);
}
/** @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 {
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);
}
/**
* @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 {
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);
}
/**
* @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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_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), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return 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), "ERC721: owner query for nonexistent token");
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, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_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), "ERC721: approved query for nonexistent token");
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 != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(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 {IERC721Receiver-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 {IERC721Receiver-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 _msgSender() 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 {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @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) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool 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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @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
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @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, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
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);
}
}
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* 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;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
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}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @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];
}
}
}
contract NFT is ERC721Metadata, Ownable {
string internal _contractURI;
constructor(string memory name, string memory symbol)
public
ERC721Metadata(name, symbol)
{}
function contractURI() external view returns (string memory) {
return _contractURI;
}
function mint(address to, uint256 tokenId) external onlyOwner {
_safeMint(to, tokenId);
}
function burn(uint256 tokenId) external onlyOwner {
_burn(tokenId);
}
function setContractURI(string calldata newURI) external onlyOwner {
_contractURI = newURI;
}
function setTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
_setTokenURI(tokenId, newURI);
}
function setBaseURI(string calldata newURI) external onlyOwner {
_setBaseURI(newURI);
}
}
contract ATokenMock is ERC20, ERC20Detailed {
using SafeMath for uint256;
using DecMath for uint256;
uint256 internal constant YEAR = 31556952; // Number of seconds in one Gregorian calendar year (365.2425 days)
ERC20 public dai;
uint256 public liquidityRate;
uint256 public normalizedIncome;
address[] public users;
mapping(address => bool) public isUser;
constructor(address _dai)
public
ERC20Detailed("aDAI", "aDAI", 18)
{
dai = ERC20(_dai);
liquidityRate = 10 ** 26; // 10% APY
normalizedIncome = 10 ** 27;
}
function redeem(uint256 _amount) external {
_burn(msg.sender, _amount);
dai.transfer(msg.sender, _amount);
}
function mint(address _user, uint256 _amount) external {
_mint(_user, _amount);
if (!isUser[_user]) {
users.push(_user);
isUser[_user] = true;
}
}
function mintInterest(uint256 _seconds) external {
uint256 interest;
address user;
for (uint256 i = 0; i < users.length; i++) {
user = users[i];
interest = balanceOf(user).mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27));
_mint(user, interest);
}
normalizedIncome = normalizedIncome.mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27)).add(normalizedIncome);
}
function setLiquidityRate(uint256 _liquidityRate) external {
liquidityRate = _liquidityRate;
}
}
contract CERC20Mock is ERC20, ERC20Detailed {
address public dai;
uint256 internal _supplyRate;
uint256 internal _exchangeRate;
constructor(address _dai) public ERC20Detailed("cDAI", "cDAI", 8) {
dai = _dai;
uint256 daiDecimals = ERC20Detailed(_dai).decimals();
_exchangeRate = 2 * (10**(daiDecimals + 8)); // 1 cDAI = 0.02 DAI
_supplyRate = 45290900000; // 10% supply rate per year
}
function mint(uint256 amount) external returns (uint256) {
require(
ERC20(dai).transferFrom(msg.sender, address(this), amount),
"Error during transferFrom"
); // 1 DAI
_mint(msg.sender, (amount * 10**18) / _exchangeRate);
return 0;
}
function redeemUnderlying(uint256 amount) external returns (uint256) {
_burn(msg.sender, (amount * 10**18) / _exchangeRate);
require(
ERC20(dai).transfer(msg.sender, amount),
"Error during transfer"
); // 1 DAI
return 0;
}
function exchangeRateStored() external view returns (uint256) {
return _exchangeRate;
}
function exchangeRateCurrent() external view returns (uint256) {
return _exchangeRate;
}
function _setExchangeRateStored(uint256 _rate) external returns (uint256) {
_exchangeRate = _rate;
}
function supplyRatePerBlock() external view returns (uint256) {
return _supplyRate;
}
function _setSupplyRatePerBlock(uint256 _rate) external {
_supplyRate = _rate;
}
}
contract ERC20Mock is ERC20, ERC20Detailed("", "", 6) {
function mint(address to, uint256 amount) public {
_mint(to, amount);
}
}
contract VaultMock is ERC20, ERC20Detailed {
using SafeMath for uint256;
using DecMath for uint256;
ERC20 public underlying;
constructor(address _underlying) public ERC20Detailed("yUSD", "yUSD", 18) {
underlying = ERC20(_underlying);
}
function deposit(uint256 tokenAmount) public {
uint256 sharePrice = getPricePerFullShare();
_mint(msg.sender, tokenAmount.decdiv(sharePrice));
underlying.transferFrom(msg.sender, address(this), tokenAmount);
}
function withdraw(uint256 sharesAmount) public {
uint256 sharePrice = getPricePerFullShare();
uint256 underlyingAmount = sharesAmount.decmul(sharePrice);
_burn(msg.sender, sharesAmount);
underlying.transfer(msg.sender, underlyingAmount);
}
function getPricePerFullShare() public view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
return 10**18;
}
return underlying.balanceOf(address(this)).decdiv(_totalSupply);
}
}
contract EMAOracle is IInterestOracle {
using SafeMath for uint256;
using DecMath for uint256;
uint256 internal constant PRECISION = 10**18;
/**
Immutable parameters
*/
uint256 public UPDATE_INTERVAL;
uint256 public UPDATE_MULTIPLIER;
uint256 public ONE_MINUS_UPDATE_MULTIPLIER;
/**
Public variables
*/
uint256 public emaStored;
uint256 public lastIncomeIndex;
uint256 public lastUpdateTimestamp;
/**
External contracts
*/
IMoneyMarket public moneyMarket;
constructor(
uint256 _emaInitial,
uint256 _updateInterval,
uint256 _smoothingFactor,
uint256 _averageWindowInIntervals,
address _moneyMarket
) public {
emaStored = _emaInitial;
UPDATE_INTERVAL = _updateInterval;
lastUpdateTimestamp = now;
uint256 updateMultiplier = _smoothingFactor.div(_averageWindowInIntervals.add(1));
UPDATE_MULTIPLIER = updateMultiplier;
ONE_MINUS_UPDATE_MULTIPLIER = PRECISION.sub(updateMultiplier);
moneyMarket = IMoneyMarket(_moneyMarket);
lastIncomeIndex = moneyMarket.incomeIndex();
}
function updateAndQuery() public returns (bool updated, uint256 value) {
uint256 timeElapsed = now - lastUpdateTimestamp;
if (timeElapsed < UPDATE_INTERVAL) {
return (false, emaStored);
}
// save gas by loading storage variables to memory
uint256 _lastIncomeIndex = lastIncomeIndex;
uint256 _emaStored = emaStored;
uint256 newIncomeIndex = moneyMarket.incomeIndex();
uint256 incomingValue = newIncomeIndex.sub(_lastIncomeIndex).decdiv(_lastIncomeIndex).div(timeElapsed);
updated = true;
value = incomingValue.mul(UPDATE_MULTIPLIER).add(_emaStored.mul(ONE_MINUS_UPDATE_MULTIPLIER)).div(PRECISION);
emaStored = value;
lastIncomeIndex = newIncomeIndex;
lastUpdateTimestamp = now;
}
function query() public view returns (uint256 value) {
return emaStored;
}
}
contract MPHToken is ERC20, ERC20Detailed, Ownable {
constructor() public ERC20Detailed("88mph.app", "MPH", 18) {}
function ownerMint(address account, uint256 amount)
public
onlyOwner
returns (bool)
{
_mint(account, amount);
return true;
}
function ownerTransfer(
address from,
address to,
uint256 amount
) public onlyOwner returns (bool) {
_transfer(from, to, amount);
return true;
}
}
|
Transfer `amount` stablecoin from `msg.sender` Approve `amount` stablecoin to lendingPool Deposit `amount` stablecoin to lendingPool
|
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "AaveMarket: amount is 0");
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
address lendingPoolCore = provider.getLendingPoolCore();
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
stablecoin.safeIncreaseAllowance(lendingPoolCore, amount);
lendingPool.deposit(address(stablecoin), amount, REFERRALCODE);
}
| 7,369,964 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "./utils/CitizenNFTTest.sol";
import "../CitizenNFT.sol";
contract NewCityDAOCitizen is CitizenTest {
/// @notice Mint new Citizen NFTs, verify that owners are correct and balance of smart contract
/// is equal to the value transfered for the minting.
string[] hashes;
uint256[] tokenIds;
function testBuyCitizenNFT() public {
payable(address(bob)).transfer(1 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 1);
bob.onlineApplicationForCitizenship(tokenPrice, 1);
assertEq(citizenNFT.balanceOf(address(bob), citizenNFTInternalId), 2);
assertEq(address(citizenNFT).balance, 2 * tokenPrice);
}
/// @notice Output the tokenURI in base64 format to be used in a decoder and observe the json metadata
function testTokenURI() public {
payable(address(bob)).transfer(1 ether);
bob.onlineApplicationForCitizenship(250000000000000000, 1);
string memory meta = citizenNFT.uri(citizenNFTInternalId);
string memory uri = "data:application/json;base64,eyAibmFtZSI6ICJDaXR5REFPIENpdGl6ZW4iLCAiZGVzY3JpcHRpb24iIDogIkEgQ2l0aXplbiBvZiBDaX"
"R5REFPIGhvbGRzIGdvdmVybmFuY2UgaW4gdGhlIG9wZXJhdGlvbnMgYW5kIGFjdGl2aXRpZXMgb2YgQ2l0eURBTy4iLCJpbWFnZSI6ICJpcGZzOi8vUW1S"
"Um51SFZ3aG9ZRUhzVHh6TWNHZHJDZnRoS1RTNjZnbmZVcURaa3Y2a2J6YSJ9";
assertEq(meta, uri);
emit log(meta);
}
function testChangeTokenURI() public {
hashes.push("rekt");
tokenIds.push(citizenNFTInternalId);
odys.changeURIs(hashes, tokenIds);
string memory meta = citizenNFT.uri(citizenNFTInternalId);
string memory uri = "data:application/json;base64,eyAibmFtZSI6ICJDaXR5REFPIENpdGl6ZW4iLCAiZGVzY3JpcHRpb24iIDogIkEgQ2l0aXplbiBvZiBDa"
"XR5REFPIGhvbGRzIGdvdmVybmFuY2UgaW4gdGhlIG9wZXJhdGlvbnMgYW5kIGFjdGl2aXRpZXMgb2YgQ2l0eURBTy4iLCJpbWFnZSI6ICJyZWt0In0=";
assertEq(meta, uri);
emit log(meta);
}
}
contract Legislate is CitizenTest {
/// @notice Test the change of cost for acquiring a citizen NFT.
/// The test is fuzzed, meaning that it will test many different values as arguments
function testOwnerChangeCitizenCost(uint96 _weiAmmount) public {
_weiAmmount = _weiAmmount % 100000000000000000000;
odys.legislateCostOfEntry(_weiAmmount);
payable(address(bob)).transfer(10000 ether);
bob.onlineApplicationForCitizenship(_weiAmmount * 10, 10);
assertEq(citizenNFT.balanceOf(address(bob), citizenNFTInternalId), 10);
assertEq(citizenNFT.inquireCostOfEntry(), _weiAmmount);
}
/// @notice Test the change of the maximum number regular Citizen NFTs that can be minted
/// The test is fuzzed, meaning that it will test many different values as arguments
function testOwnerChangeCitizensNumber(uint96 _housingNumber) public {
odys.buildHousing(_housingNumber);
uint256 housingNumbers = citizenNFT.inquireHousingNumbers();
uint256 mintedNFTs = uint256(_housingNumber) + 10000;
assertEq(mintedNFTs, housingNumbers);
}
/// @notice Test the change of the maximum number of founding Citizen NFTs that can be minted
function testRewriteHistory(uint96 _numberOfNewFoundingCitizens) public {
odys.rewriteHistory(_numberOfNewFoundingCitizens);
assertEq(
citizenNFT.inquireAboutHistory(),
uint256(_numberOfNewFoundingCitizens) + 50
);
}
/// @notice If a non-owner tries to affect the cost of regular Citizen NFTs, it should fail
function testFailnonOwnerChangeCitizenCost(uint96 _weiAmmount) public {
_weiAmmount = _weiAmmount % 100000000000000000000;
bob.legislateCostOfEntry(_weiAmmount);
}
/// @notice If a non-owner user tries to affect the maximum number of regular Citizen NFTs, it should fail
function testFailChangeCitizensNumber(uint256 _housingNumber) public {
bob.buildHousing(_housingNumber);
}
/// @notice The owner should be able to withdraw the funds that exist in the smart contract
function testRaidTheCoffers() public {
payable(address(bob)).transfer(1 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 2);
odys.raidTheCoffers();
assertEq(address(odys).balance, tokenPrice * 2);
}
function testFailtCallInitAgain() public {
odys.initialCitizenship();
}
function testFailReserveCitizenships() public {
odys.reserveCitizenships(1000);
payable(address(bob)).transfer(5000 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 9000);
emit log_uint(
citizenNFT.balanceOf(address(odys), citizenNFTInternalId)
);
}
function testReserveCitizenships() public {
odys.reserveCitizenships(500);
payable(address(bob)).transfer(5000 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 9000);
assertEq(
citizenNFT.balanceOf(address(bob), citizenNFTInternalId),
9000
);
assertEq(
citizenNFT.balanceOf(address(odys), citizenNFTInternalId),
1000
);
}
}
contract Royalties is CitizenTest {
function testDefaultRoyalties() public {
(address receiver, uint256 royalty) = citizenNFT.royaltyInfo(42, 10);
assertEq(receiver, defaultRoyaltyReceiver);
assertEq(royalty, 1);
}
function testTokenRoyalty() public {
odys.setTokenRoyalty(69, address(odys), 3000);
(address receiver, uint256 royalty) = citizenNFT.royaltyInfo(69, 1000);
assertEq(receiver, address(odys));
assertEq(royalty, 300);
}
}
contract Airdrop is CitizenTest {
uint256[] tokenNumbers;
address[] addresses;
function testAirdrop() public {
tokenNumbers = [10, 5];
addresses = [address(bob), address(alice)];
odys.awardCitizenship(addresses, tokenNumbers, 42);
tokenNumbers = [1, 23];
odys.awardCitizenship(addresses, tokenNumbers, 69);
assertEq(citizenNFT.balanceOf(address(bob), 42), 10);
assertEq(citizenNFT.balanceOf(address(alice), 42), 5);
assertEq(citizenNFT.balanceOf(address(bob), 69), 1);
assertEq(citizenNFT.balanceOf(address(alice), 69), 23);
}
function testFailAirdropNotUser() public {
tokenNumbers = [10, 5];
addresses = [address(bob), address(alice)];
bob.awardCitizenship(addresses, tokenNumbers, 42);
}
}
|
If a non-owner tries to affect the cost of regular Citizen NFTs, it should fail
|
function testFailnonOwnerChangeCitizenCost(uint96 _weiAmmount) public {
_weiAmmount = _weiAmmount % 100000000000000000000;
bob.legislateCostOfEntry(_weiAmmount);
}
| 6,460,136 |
./full_match/3/0x0F393948bE6D63cB687153152265709B7600D8b3/sources/contracts/FireNFT.sol
|
Mint masterNFT For Free/ Test _masterTokenCounter Incrementing ID to create new token
|
function _mintMasterNFT(address sender) internal returns(uint256){
require(_masterTokenCounter.current() < MAX_MASTER_NFT_SUPPLY, "Master NFT Minting has already ended");
require(balanceOf(sender) < MAX_MASTER_NFT_SUPPLY_PER_USER, "Master NFT Minting has already ended");
uint256 newMasterNFTID = _masterTokenCounter.current();
_masterTokenCounter.increment();
_safeMint(sender, newMasterNFTID);
return newMasterNFTID;
}
| 8,264,986 |
./partial_match/42/0xFae5AF1252837c4Ad4BbB16A1f4bDB846D1FED0c/sources/Issuer.sol
|
it's more gas intensive to put this check here if they have 0 PNX, but it complies with the interface
|
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedPynthetix = _collateral(_issuer);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PNX);
if (totalOwnedPynthetix == 0) return (0, anyRateIsInvalid);
return (debtBalance.divideDecimalRound(totalOwnedPynthetix), anyRateIsInvalid);
}
| 3,444,373 |
pragma solidity ^0.5.0;
// Import the `Roles` library
import "../milkcore/Ownable.sol";
import "../milkaccesscontrol/PoultererRole.sol";
import "../milkaccesscontrol/DairyfactoryRole.sol";
import "../milkaccesscontrol/DistributorRole.sol";
import "../milkaccesscontrol/RetailerRole.sol";
import "../milkaccesscontrol/SupermarketRole.sol";
import "../milkaccesscontrol/ConsumerRole.sol";
// Define a contract 'Supplychain'
contract SupplyChain is Ownable, PoultererRole, DairyfactoryRole, DistributorRole, RetailerRole, SupermarketRole, ConsumerRole {
// Define 'owner'
//address owner;
// 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;
// Define a public mapping 'itemsHistory' that maps the UPC to an array of TxHash,
// that track its journey through the supply chain -- to be sent from DApp.
mapping (uint => string[]) itemsHistory;
// Define enum 'State' with the following values:
enum State
{
Obtained, // 0
Stored, // 1
ForSaleToDairyfactory, // 2
SoldToDairyfactory, // 3
ShippedToDairyfactory, // 4
ReceivedByDairyfactory, // 5
Tested, // 6
Qualified, // 7
Failed, // 8
Processed, // 9
Returned, // 10
Retaken, // 11
ShippedToPoulterer, // 12
ReceivedByPoulterer, // 13
Destroyed, // 14
Packed, // 15
ForSaleToDistributor, // 16
SoldToDistributor, // 17
ShippedToDistributor, // 18
ReceivedByDistributor, // 19
ForSaleToRetailer, // 20
SoldToRetailer, // 21
ShippedToRetailer, // 22
ReceivedByRetailer, // 23
ForSaleToSupermarket, // 24
SoldToSupermarket, // 25
ShippedToSupermarket, // 26
ReceivedBySupermarket, // 27
ForSaleToConsumer, // 28
SoldToConsumer, // 29
PurchasedByConsumer // 30
}
State constant defaultState = State.Obtained;
// 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 Poulterer, goes on the package, can be verified by the Consumer
bool existItem; // Boolean to check the existence of the item easily
address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through 31 stages
address payable originPoultererID; // Metamask-Ethereum address of the Poulterer
string originFarmName; // Poulterer Name
string originFarmInformation; // Poulterer 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
bool isQualified; // The quality status of the milk.
State itemState; // Product State as represented in the enum above
address payable dairyfactoryID; // Metamask-Ethereum address of the Dairyfactory
address payable distributorID; // Metamask-Ethereum address of the Distributor
address payable retailerID; // Metamask-Ethereum address of the Retailer
address payable supermarketID; // Metamask-Ethereum address of the Supermarket
address payable consumerID; // Metamask-Ethereum address of the Consumer
}
// Define 15 events with the same 15 state values and accept 'upc' as input argument
event Obtained(uint upc, address emiter);
event Stored(uint upc, address emiter);
event ForSaleToDairyfactory(uint upc, address emiter, uint price);
event SoldToDairyfactory(uint upc, address emiter);
event ShippedToDairyfactory(uint upc, address emiter);
event ReceivedByDairyfactory(uint upc, address emiter);
event Tested(uint upc, address emiter, bool testResult);
event Processed(uint upc, address emiter);
event Returned(uint upc, address emiter);
event Retaken(uint upc, address emiter);
event ShippedToPoulterer(uint upc, address emiter);
event ReceivedByPoulterer(uint upc, address emiter);
event Destroyed(uint upc, address emiter);
event Packed(uint upc, address emiter);
event ForSaleToDistributor(uint upc, address emiter, uint price);
event SoldToDistributor(uint upc, address emiter);
event ShippedToDistributor(uint upc, address emiter);
event ReceivedByDistributor(uint upc, address emiter);
event ForSaleToRetailer(uint upc, address emiter, uint price);
event SoldToRetailer(uint upc, address emiter);
event ShippedToRetailer(uint upc, address emiter);
event ReceivedByRetailer(uint upc, address emiter);
event ForSaleToSupermarket(uint upc, address emiter, uint price);
event SoldToSupermarket(uint upc, address emiter);
event ShippedToSupermarket(uint upc, address emiter);
event ReceivedBySupermarket(uint upc, address emiter);
event ForSaleToConsumer(uint upc, address emiter, uint price);
event SoldToConsumer(uint upc, address emiter);
event PurchasedByConsumer(uint upc, address emiter);
// Define a modifer that verifies the Caller
modifier verifyCaller (address _address) {
require(msg.sender == _address);
_;
}
// Define a modifier that checks if the paid amount is sufficient to cover the price
modifier paidEnough(uint _price) {
require(msg.value >= _price);
_;
}
// 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;
msg.sender.transfer(amountToReturn);
}
// Define a modifier that checks if an item.state of a upc is Sold
modifier checkItemState (uint _upc, State _state, string memory _errorMessage){
require(items[_upc].itemState == _state, _errorMessage);
_;
}
// Define a modifier that checks if a _upc is already in the items mapping
modifier checkUpcInItems(uint _upc) {
require(items[_upc].existItem, "This UPC does not exist in items mapping.");
_;
}
// In the constructor set 'owner' to the address that instantiated the contract
// and set 'sku' to 1
// and set 'upc' to 1
constructor() public payable {
sku = 1;
upc = 1;
}
// Define a function 'kill' if required
function kill() public {
selfdestruct(this.owner());
}
// Define a function 'obtainItem' that allows a poulterer to mark an item 'Obtained'
function obtainItem(
uint _upc,
address payable _originPoultererID,
string memory _originFarmName,
string memory _originFarmInformation,
string memory _originFarmLatitude,
string memory _originFarmLongitude,
string memory _productNotes)
public onlyPoulterer()
{
// Add the new item as part of Obtain
Item memory newItem = Item(
sku, // Stock Keeping Unit (SKU)
_upc, // Universal Product Code (UPC)
true, // Boolean to check the existence of the item easily
_originPoultererID, // Metamask-Ethereum address of the current owner
_originPoultererID, // Metamask-Ethereum address of the Poulterer
_originFarmName, // Poulterer Name
_originFarmInformation, // Poulterer Information
_originFarmLatitude, // Farm Latitude
_originFarmLongitude, // Farm Longitude
_upc + sku, // Product ID
_productNotes, // Product Note
0, // Product Price
false, // The quality status of milk.
State.Obtained, // Product State
address(0), // Metamask-Ethereum address of the Dairyfactory
address(0), // Metamask-Ethereum address of the Distributor
address(0), // Metamask-Ethereum address of the Retailer
address(0), // Metamask-Ethereum address of the Supermarket
address(0) // Metamask-Ethereum address of the Consumer
);
items[_upc] = newItem;
// Increment sku
sku = sku + 1;
// Emit the appropriate event
emit Obtained(_upc, msg.sender);
}
// Define a function 'StoreItem' that allows a poulterer to mark an item 'Stored'
function storeItem(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
checkItemState (_upc, State.Obtained, "Milk is not obtained!")
verifyCaller(items[_upc].ownerID) // Check the caller is the owner of the item
{
// Update the appropriate fields
items[_upc].itemState = State.Stored;
// Emit the appropriate event
emit Stored(_upc, msg.sender);
}
// Define a function 'sellToDairyfactory' that allows a poulterer to mark an item 'ForSaleToDairyfactory'
function sellToDairyfactory(uint _upc, uint _price) public
onlyPoulterer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.Stored, "Milk is not stored!")
{
// Update the appropriate fields
items[_upc].itemState = State.ForSaleToDairyfactory;
items[_upc].productPrice = _price;
// Emit the appropriate event
emit ForSaleToDairyfactory(_upc, msg.sender, _price);
}
// Define a function 'buyItemByDairyfactory' that allows the dairyfactory to mark an item 'SoldToDairyfactory'
// 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
function buyItemByDairyfactory(uint _upc) public payable
onlyDairyfactory()
checkUpcInItems (_upc)
checkItemState (_upc, State.ForSaleToDairyfactory, "Milk is not for sale to dairyfactory!")
paidEnough(items[_upc].productPrice) // Check if buyer has paid enough
checkValue(_upc) // Send any excess Ether back to buyer
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].ownerID = msg.sender;
items[_upc].dairyfactoryID = msg.sender;
items[_upc].itemState = State.SoldToDairyfactory;
// Transfer money to poulterer
items[_upc].originPoultererID.transfer(items[_upc].productPrice);
// emit the appropriate event
emit SoldToDairyfactory(_upc, msg.sender);
}
// Define a function 'shipItemToDairyfactory' that allows the poulterer to mark an item 'ShippedToDairyfactory'
// Use the above modifers to check if the item is sold
function shipItemToDairyfactory(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item
checkItemState (_upc, State.SoldToDairyfactory, "Milk is not sold to dairyfactory!")
{
// Update the appropriate fields
items[_upc].itemState = State.ShippedToDairyfactory;
// Emit the appropriate event
emit ShippedToDairyfactory(_upc, msg.sender);
}
// Define a function 'receiveItemByDairyfactory' that allows the dairyfactory to mark an item 'ReceivedByDairyfactory'
// Use the above modifiers to check if the item is shipped
function receiveItemByDairyfactory(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ShippedToDairyfactory, "Milk is not shipped to dairyfactory!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.ReceivedByDairyfactory;
// Emit the appropriate event
emit ReceivedByDairyfactory(_upc, msg.sender);
}
// Define a function 'testMilk' that allows the dairyfactory to mark an item 'Qualified or Failed'
// Use the above modifiers to check if the item is received
function testMilk(uint _upc, bool _testResult) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedByDairyfactory, "Milk is not received by dairyfactory!")
{
if (_testResult) {
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Qualified;
// Emit the appropriate event
//emit Qualified(_upc, msg.sender);
} else {
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Failed;
// Emit the appropriate event
//emit Failed(_upc, msg.sender);
}
}
// Define a function 'processMilk' that allows the dairyfactory to mark an item 'Processed'
// Use the above modifiers to check if the item is qualified
function processMilk(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedByDairyfactory, "Milk is not qualified the quality test!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Processed;
// Emit the appropriate event
emit Processed(_upc, msg.sender);
}
// Define a function 'returnMilk' that allows the dairyfactory to mark an item 'Returned'
// Use the above modifiers to check if the item is qualified
function returnMilk(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.Failed, "Milk is not failed the quality test!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Returned;
// Emit the appropriate event
emit Returned(_upc, msg.sender);
}
// Define a function 'retakeMilk' that allows the poulterer to mark an item 'Retaken'
function retakeMilk(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item
checkItemState (_upc, State.Returned, "Milk is not returned to poulterer!")
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].itemState = State.Retaken;
// emit the appropriate event
emit Retaken(_upc, msg.sender);
}
// Define a function 'shipItemToPoulterer' that allows the dairy factory to mark an item 'ShippedToPoulterer'
// Use the above modifers to check if the item is retaken
function shipItemToPoulterer(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].originPoultererID) // Check if caller is the poulterer of the item
checkItemState (_upc, State.Retaken, "Milk is not retaken by dairy factory!")
{
// Update the appropriate fields
items[_upc].itemState = State.ShippedToPoulterer;
// Emit the appropriate event
emit ShippedToPoulterer(_upc, msg.sender);
}
// Define a function 'receiveItemByPoulterer' that allows the dairyfactory to mark an item 'ReceivedByPoulterer'
// Use the above modifiers to check if the item is ShippedToPoulterer
function receiveItemByPoulterer(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ShippedToPoulterer, "Milk is not shipped to poulterer!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.ReceivedByPoulterer;
// Emit the appropriate event
emit ReceivedByPoulterer(_upc, msg.sender);
}
// Define a function 'destroyMilk' that allows the poulterer to mark an item 'Destroyed'
// Use the above modifiers to check if the item is ReceivedByPoulterer
function destroyMilk(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedByPoulterer, "Milk is not received by poulterer!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Destroyed;
// Emit the appropriate event
emit Destroyed(_upc, msg.sender);
}
// Define a function 'packMilk' that allows the dairy factory to mark an item 'Packed'
// Use the above modifiers to check if the item is processed
function packMilk(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.Processed, "Milk is not processed!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.Packed;
// Emit the appropriate event
emit Packed(_upc, msg.sender);
}
// Define a function 'sellToDistributor' that allows a dairy factory to mark an item 'ForSaleToDistributor'
function sellToDistributor(uint _upc, uint _price) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].ownerID) // Check if caller is the owner of the item
checkItemState (_upc, State.Packed, "Milk is not packed!")
{
// Update the appropriate fields
items[_upc].itemState = State.ForSaleToDistributor;
items[_upc].productPrice = _price;
// Emit the appropriate event
emit ForSaleToDistributor(_upc, msg.sender, _price);
}
// Define a function 'buyItemByDistributor' that allows the distributor to mark an item 'SoldToDistributor'
// 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
function buyItemByDistributor(uint _upc) public payable
onlyDistributor()
checkUpcInItems (_upc)
checkItemState (_upc, State.ForSaleToDistributor, "Milk is not for sale to distributor!")
paidEnough(items[_upc].productPrice) // Check if buyer has paid enough
checkValue(_upc) // Send any excess Ether back to buyer
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].ownerID = msg.sender;
items[_upc].distributorID = msg.sender;
items[_upc].itemState = State.SoldToDistributor;
// Transfer money to poulterer
items[_upc].dairyfactoryID.transfer(items[_upc].productPrice);
// emit the appropriate event
emit SoldToDistributor(_upc, msg.sender);
}
// Define a function 'shipItemToDistributor' that allows the dairy factory to mark an item 'ShippedToDistributor'
// Use the above modifers to check if the item is sold
function shipItemToDistributor(uint _upc) public
onlyDairyfactory()
checkUpcInItems (_upc)
verifyCaller(items[_upc].dairyfactoryID) // Check if caller is the owner of the item
checkItemState (_upc, State.SoldToDistributor, "Milk is not sold to distributor!")
{
// Update the appropriate fields
items[_upc].itemState = State.ShippedToDistributor;
// Emit the appropriate event
emit ShippedToDistributor(_upc, msg.sender);
}
// Define a function 'receiveItemByDistributor' that allows the distributor to mark an item 'ReceivedByDistributor'
// Use the above modifiers to check if the item is shipped
function receiveItemByDistributor(uint _upc) public
onlyDistributor()
checkUpcInItems (_upc)
verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item
checkItemState (_upc, State.ShippedToDistributor, "Milk is not shipped to distributor!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.ReceivedByDistributor;
// Emit the appropriate event
emit ReceivedByDistributor(_upc, msg.sender);
}
// Define a function 'sellToRetailer' that allows a dairy factory to mark an item 'ForSaleToRetailer'
function sellToRetailer(uint _upc, uint _price) public
onlyDistributor()
checkUpcInItems (_upc)
verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedByDistributor, "Milk is not received by distributor!")
{
// Update the appropriate fields
items[_upc].itemState = State.ForSaleToRetailer;
items[_upc].productPrice = _price;
// Emit the appropriate event
emit ForSaleToRetailer(_upc, msg.sender, _price);
}
// Define a function 'buyItemByRetailer' that allows the retailer to mark an item 'SoldToRetailer'
// 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
function buyItemByRetailer(uint _upc) public payable
onlyRetailer()
checkUpcInItems (_upc)
checkItemState (_upc, State.ForSaleToRetailer, "Milk is not for sale to retailer!")
paidEnough(items[_upc].productPrice) // Check if buyer has paid enough
checkValue(_upc) // Send any excess Ether back to buyer
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].ownerID = msg.sender;
items[_upc].retailerID = msg.sender;
items[_upc].itemState = State.SoldToRetailer;
// Transfer money to poulterer
items[_upc].distributorID.transfer(items[_upc].productPrice);
// emit the appropriate event
emit SoldToRetailer(_upc, msg.sender);
}
// Define a function 'shipItemToRetailer' that allows the distributor to mark an item 'ShippedToRetailer'
// Use the above modifers to check if the item is sold
function shipItemToRetailer(uint _upc) public
onlyDistributor()
checkUpcInItems (_upc)
verifyCaller(items[_upc].distributorID) // Check if caller is the owner of the item
checkItemState (_upc, State.SoldToRetailer, "Milk is not sold to retailer!")
{
// Update the appropriate fields
items[_upc].itemState = State.ShippedToRetailer;
// Emit the appropriate event
emit ShippedToRetailer(_upc, msg.sender);
}
// Define a function 'receiveItemByRetailer' that allows the retailer to mark an item 'ReceivedByRetailer'
// Use the above modifiers to check if the item is shipped
function receiveItemByRetailer(uint _upc) public
onlyRetailer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ShippedToRetailer, "Milk is not shipped to retailer!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.ReceivedByRetailer;
// Emit the appropriate event
emit ReceivedByRetailer(_upc, msg.sender);
}
// Define a function 'sellToSuperMarket' that allows a retailer to mark an item 'ForSaleToSupermarket'
function sellToSuperMarket(uint _upc, uint _price) public
onlyRetailer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedByRetailer, "Milk is not received by retailer!")
{
// Update the appropriate fields
items[_upc].itemState = State.ForSaleToSupermarket;
items[_upc].productPrice = _price;
// Emit the appropriate event
emit ForSaleToSupermarket(_upc, msg.sender, _price);
}
// Define a function 'buyItemBySupermarket' that allows the supermarket to mark an item 'SoldToSupermarket'
// 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
function buyItemBySupermarket(uint _upc) public payable
onlySupermarket()
checkUpcInItems (_upc)
checkItemState (_upc, State.ForSaleToSupermarket, "Milk is not for sale to supermarket!")
paidEnough(items[_upc].productPrice) // Check if buyer has paid enough
checkValue(_upc) // Send any excess Ether back to buyer
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].ownerID = msg.sender;
items[_upc].supermarketID = msg.sender;
items[_upc].itemState = State.SoldToSupermarket;
// Transfer money to poulterer
items[_upc].retailerID.transfer(items[_upc].productPrice);
// emit the appropriate event
emit SoldToSupermarket(_upc, msg.sender);
}
// Define a function 'shipItemToSupermarket' that allows the retailer to mark an item 'ShippedToSupermarket'
// Use the above modifers to check if the item is sold
function shipItemToSupermarket(uint _upc) public
onlyRetailer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].retailerID) // Check if caller is the owner of the item
checkItemState (_upc, State.SoldToSupermarket, "Milk is not sold to supermarket!")
{
// Update the appropriate fields
items[_upc].itemState = State.ShippedToSupermarket;
// Emit the appropriate event
emit ShippedToSupermarket(_upc, msg.sender);
}
// Define a function 'receiveItemBySupermarket' that allows the retailer to mark an item 'ReceivedBySupermarket'
// Use the above modifiers to check if the item is shipped
function receiveItemBySupermarket(uint _upc) public
onlySupermarket()
checkUpcInItems (_upc)
verifyCaller(items[_upc].supermarketID) // Check if caller is the owner of the item
checkItemState (_upc, State.ShippedToSupermarket, "Milk is not shipped to supermarket!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.ReceivedBySupermarket;
// Emit the appropriate event
emit ReceivedBySupermarket(_upc, msg.sender);
}
// Define a function 'sellToConsumer' that allows a supermarket to mark an item 'ForSaleToConsumer'
function sellToConsumer(uint _upc, uint _price) public
onlySupermarket()
checkUpcInItems (_upc)
verifyCaller(items[_upc].supermarketID) // Check if caller is the owner of the item
checkItemState (_upc, State.ReceivedBySupermarket, "Milk is not received by supermarket!")
{
// Update the appropriate fields
items[_upc].itemState = State.ForSaleToConsumer;
items[_upc].productPrice = _price;
// Emit the appropriate event
emit ForSaleToConsumer(_upc, msg.sender, _price);
}
// Define a function 'buyItemByConsumer' that allows the supermarket to mark an item 'SoldToConsumer'
// 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
function buyItemByConsumer(uint _upc) public payable
onlyConsumer()
checkUpcInItems (_upc)
checkItemState (_upc, State.ForSaleToConsumer, "Milk is not for sale to consumer!")
paidEnough(items[_upc].productPrice) // Check if buyer has paid enough
checkValue(_upc) // Send any excess Ether back to buyer
{
// Update the appropriate fields - ownerID, dairyfactoryID, itemState
items[_upc].ownerID = msg.sender;
items[_upc].consumerID = msg.sender;
items[_upc].itemState = State.SoldToConsumer;
// Transfer money to poulterer
items[_upc].supermarketID.transfer(items[_upc].productPrice);
// emit the appropriate event
emit SoldToConsumer(_upc, msg.sender);
}
// Define a function 'purchaseItemByConsumer' that allows the consumer to mark an item 'PurchasedByConsumer'
// Use the above modifiers to check if the item is received
function purchaseItemByConsumer(uint _upc) public
onlyConsumer()
checkUpcInItems (_upc)
verifyCaller(items[_upc].consumerID) // Check if caller is the owner of the item
checkItemState (_upc, State.SoldToConsumer, "Milk is not sold to consumer!")
{
// Update the appropriate fields - ownerID, retailerID, itemState
items[_upc].itemState = State.PurchasedByConsumer;
// Emit the appropriate event
emit PurchasedByConsumer(_upc, msg.sender);
}
// Define a function 'fetchItemBufferPublic' that fetches the public data
function fetchItemBufferPublic(uint _upc) public checkUpcInItems(_upc) view returns
(
uint itemSKU,
uint itemUPC,
address ownerID,
address originPoultererID,
string memory originFarmName,
string memory originFarmInformation,
string memory originFarmLatitude,
string memory originFarmLongitude,
State itemState,
uint productPrice,
address distributorID
)
{
// Assign values to the parameters
Item memory foundedItem = items[_upc];
itemSKU = foundedItem.sku;
itemUPC = foundedItem.upc;
ownerID = foundedItem.ownerID;
originPoultererID = foundedItem.originPoultererID;
originFarmName = foundedItem.originFarmName;
originFarmInformation = foundedItem.originFarmInformation;
originFarmLatitude = foundedItem.originFarmLatitude;
originFarmLongitude = foundedItem.originFarmLongitude;
itemState = foundedItem.itemState;
productPrice = foundedItem.productPrice;
distributorID = foundedItem.distributorID;
return
(
itemSKU,
itemUPC,
ownerID,
originPoultererID,
originFarmName,
originFarmInformation,
originFarmLatitude,
originFarmLongitude,
itemState,
productPrice,
distributorID
);
}
// Define a function 'fetchItemBufferForDistributor' that fetches the data only for distributor
function fetchItemBufferDistributor(uint _upc) public checkUpcInItems(_upc) view returns
(
uint itemSKU,
uint itemUPC,
address ownerID,
address distributorID,
string memory originFarmName,
string memory originFarmInformation,
string memory originFarmLatitude,
string memory originFarmLongitude,
string memory productNotes,
State itemState
)
{
// Assign values to the parameters
Item memory foundedItem = items[_upc];
itemSKU = foundedItem.sku;
itemUPC = foundedItem.upc;
ownerID = foundedItem.ownerID;
distributorID = foundedItem.distributorID;
originFarmName = foundedItem.originFarmName;
originFarmInformation = foundedItem.originFarmInformation;
originFarmLatitude = foundedItem.originFarmLatitude;
originFarmLongitude = foundedItem.originFarmLongitude;
productNotes = foundedItem.productNotes;
itemState = foundedItem.itemState;
return
(
itemSKU,
itemUPC,
ownerID,
distributorID,
originFarmName,
originFarmInformation,
originFarmLatitude,
originFarmLongitude,
productNotes,
itemState
);
}
// Define a function 'fetchItemBufferForConsumer' that fetches the data only for consumer
function fetchItemBufferConsumer(uint _upc) public checkUpcInItems(_upc) view returns
(
uint itemSKU,
uint itemUPC,
address ownerID,
address consumerID,
string memory originFarmName,
string memory productNotes,
address distributorID,
State itemState
)
{
// Assign values to the parameters
Item memory foundedItem = items[_upc];
itemSKU = foundedItem.sku;
itemUPC = foundedItem.upc;
ownerID = foundedItem.ownerID;
consumerID = foundedItem.consumerID;
originFarmName = foundedItem.originFarmName;
distributorID = foundedItem.distributorID;
productNotes = foundedItem.productNotes;
itemState = foundedItem.itemState;
return
(
itemSKU,
itemUPC,
ownerID,
consumerID,
originFarmName,
productNotes,
distributorID,
itemState
);
}
}
|
Define a function 'retakeMilk' that allows the poulterer to mark an item 'Retaken' Update the appropriate fields - ownerID, dairyfactoryID, itemState emit the appropriate event
|
function retakeMilk(uint _upc) public
onlyPoulterer()
checkUpcInItems (_upc)
checkItemState (_upc, State.Returned, "Milk is not returned to poulterer!")
{
items[_upc].itemState = State.Retaken;
emit Retaken(_upc, msg.sender);
}
| 1,004,326 |
// SPDX-License-Identifier: MIT
// GO TO LINE 1904 TO SEE WHERE THE BANANA CONTRACT STARTS
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;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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);
}
pragma solidity >=0.6.2 <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/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
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);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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 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;
// 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(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));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 EnumerableMap {
// 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 MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @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) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @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) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @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._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.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) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// 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))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings 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 => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.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) private _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.
*/
constructor (string memory name_, string memory symbol_) public {
_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 virtual 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 virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).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(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, 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 virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual 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 virtual 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 = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.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 = ERC721.ownerOf(tokenId); // internal owner
_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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
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(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <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 () 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;
}
}
//mloot
pragma solidity ^0.7.0;
pragma abicoder v2;
contract mlootcontract is ERC721, Ownable {
using SafeMath for uint256;
string public mloot_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN mloot ARE ALL SOLD OUT
string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS
bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE
uint256 public constant mlootPrice = 0;
uint public constant maxmlootPurchase = 5;
uint256 public constant MAX_mlootS = 7882;
bool public saleIsActive = false;
mapping(uint => string) public mlootNames;
// Reserve 100 mloot for team - Giveaways/Prizes etc
uint public mlootReserve = 100;
event mlootNameChange(address _by, uint _tokenId, string _name);
event licenseisLocked(string _licenseText);
constructor() ERC721("M'loot", "M'loot") { }
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function reservemloots(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= mlootReserve, "Not enough reserve lef");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
mlootReserve = mlootReserve.sub(_reserveAmount);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
mloot_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A mloot WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function claim(uint numberOfTokens) public {
require(saleIsActive, "Sale must be active to mint mloot");
require(numberOfTokens > 0 && numberOfTokens <= maxmlootPurchase, "Can only mint 5 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_mlootS, "Purchase would exceed max supply of mloot");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_mlootS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function changemlootName(uint _tokenId, string memory _name) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this mloot!");
require(sha256(bytes(_name)) != sha256(bytes(mlootNames[_tokenId])), "New name is same as the current one");
mlootNames[_tokenId] = _name;
emit mlootNameChange(msg.sender, _tokenId, _name);
}
function viewmlootName(uint _tokenId) public view returns( string memory ){
require( _tokenId < totalSupply(), "Choose a mloot within range" );
return mlootNames[_tokenId];
}
// GET ALL mloot OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
function mlootNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = mlootNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
}
|
Returns the license for tokens
|
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A mloot WITHIN RANGE");
return LICENSE_TEXT;
}
| 6,189,193 |
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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.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);
}
pragma solidity ^0.5.0;
import "./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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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.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);
}
pragma solidity ^0.5.0;
import "./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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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.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);
}
pragma solidity ^0.5.0;
import "./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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
|
return true if the vesting is revocable./
|
function revocable() public view returns (bool) {
return _revocable;
}
| 7,230,038 |
./full_match/5/0x80cacf8881F906CAA4322bb45Ccd00c640F4cB1a/sources/contracts/MyContract.sol
|
Update the value of the mapping for a token ID
|
function updateTokenNickname(
uint256 _tokenId,
string calldata _nickname
) public onlyRole(NICKNAMER_ROLE) {
tokenNicknames[_tokenId] = _nickname;
}
| 1,892,819 |
./full_match/1/0x4518cAd3aE6be7bb2b2be6541fB5d71F97Ea7C2c/sources/contracts/RiseOfTheMemes_1155.sol
|
Function allows to pause deposits if needed. Withdraw remains active./
|
function pauseDeposit(bool _pause) public onlyOwner {
depositPaused = _pause;
}
| 8,384,171 |
./partial_match/1/0x9662833c1FC8f2AfF8569816208E8f7653eC8af4/sources/YouAreTheChampion.sol
|
Calculates sqrt(a), following the selected rounding direction./
|
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
| 2,889,334 |
./full_match/4/0xf809DB345B6eFb81e1Ff58B26c41199EDb6aA9De/sources/contracts/4_JokerCharlie.sol
|
Returns the total amount of tokens stored by the contract./
|
function totalSupply() external view virtual override returns (uint256) {
return bigJokerSold + smallJokerSold;
}
| 789,995 |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
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 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);
}
contract UserRegistryInterface {
event AddAddress(address indexed who);
event AddIdentity(address indexed who);
function knownAddress(address _who) public constant returns(bool);
function hasIdentity(address _who) public constant returns(bool);
function systemAddresses(address _to, address _from) public constant returns(bool);
}
contract MultiOwners {
event AccessGrant(address indexed owner);
event AccessRevoke(address indexed owner);
mapping(address => bool) owners;
address public publisher;
function MultiOwners() public {
owners[msg.sender] = true;
publisher = msg.sender;
}
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function isOwner() public constant returns (bool) {
return owners[msg.sender] ? true : false;
}
function checkOwner(address maybe_owner) public constant returns (bool) {
return owners[maybe_owner] ? true : false;
}
function grant(address _owner) onlyOwner public {
owners[_owner] = true;
AccessGrant(_owner);
}
function revoke(address _owner) onlyOwner public {
require(_owner != publisher);
require(msg.sender != _owner);
owners[_owner] = false;
AccessRevoke(_owner);
}
}
contract TokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract TokenInterface is ERC20 {
string public name;
string public symbol;
uint public decimals;
}
contract MintableTokenInterface is TokenInterface {
address public owner;
function mint(address beneficiary, uint amount) public returns(bool);
function transferOwnership(address nextOwner) public;
}
/**
* Complex crowdsale with huge posibilities
* Core features:
* - Whitelisting
* - Min\max invest amounts
* - Only known users
* - Buy with allowed tokens
* - Oraclize based pairs (ETH to TOKEN)
* - Revert\refund
* - Personal bonuses
* - Amount bonuses
* - Total supply bonuses
* - Early birds bonuses
* - Extra distribution (team, foundation and also)
* - Soft and hard caps
* - Finalization logics
**/
contract Crowdsale is MultiOwners, TokenRecipient {
using SafeMath for uint;
// ██████╗ ██████╗ ███╗ ██╗███████╗████████╗███████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔════╝
// ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████╗
// ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ╚════██║
// ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ███████║
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══════╝
uint public constant VERSION = 0x1;
enum State {
Setup, // Non active yet (require to be setuped)
Active, // Crowdsale in a live
Claim, // Claim funds by owner
Refund, // Unsucceseful crowdsale (refund ether)
History // Close and store only historical fact of existence
}
struct PersonalBonusRecord {
uint bonus;
address refererAddress;
uint refererBonus;
}
struct WhitelistRecord {
bool allow;
uint min;
uint max;
}
// ██████╗ ██████╗ ███╗ ██╗███████╗██╗███╗ ██╗ ██████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝██║████╗ ██║██╔════╝
// ██║ ██║ ██║██╔██╗ ██║█████╗ ██║██╔██╗ ██║██║ ███╗
// ██║ ██║ ██║██║╚██╗██║██╔══╝ ██║██║╚██╗██║██║ ██║
// ╚██████╗╚██████╔╝██║ ╚████║██║ ██║██║ ╚████║╚██████╔╝
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝
bool public isWhitelisted; // Should be whitelisted to buy tokens
bool public isKnownOnly; // Should be known user to buy tokens
bool public isAmountBonus; // Enable amount bonuses in crowdsale?
bool public isEarlyBonus; // Enable early bird bonus in crowdsale?
bool public isTokenExchange; // Allow to buy tokens for another tokens?
bool public isAllowToIssue; // Allow to issue tokens with tx hash (ex bitcoin)
bool public isDisableEther; // Disable purchase with the Ether
bool public isExtraDistribution; // Should distribute extra tokens to special contract?
bool public isTransferShipment; // Will ship token via minting?
bool public isCappedInEther; // Should be capped in Ether
bool public isPersonalBonuses; // Should check personal beneficiary bonus?
bool public isAllowClaimBeforeFinalization;
// Should allow to claim funds before finalization?
bool public isMinimumValue; // Validate minimum amount to purchase
bool public isMinimumInEther; // Is minimum amount setuped in Ether or Tokens?
uint public minimumPurchaseValue; // How less buyer could to purchase
// List of allowed beneficiaries
mapping (address => WhitelistRecord) public whitelist;
// Known users registry (required to known rules)
UserRegistryInterface public userRegistry;
mapping (uint => uint) public amountBonuses; // Amount bonuses
uint[] public amountSlices; // Key is min amount of buy
uint public amountSlicesCount; // 10000 - 100.00% bonus over base pricetotaly free
// 5000 - 50.00% bonus
// 0 - no bonus at all
mapping (uint => uint) public timeBonuses; // Time bonuses
uint[] public timeSlices; // Same as amount but key is seconds after start
uint public timeSlicesCount;
mapping (address => PersonalBonusRecord) public personalBonuses;
// personal bonuses
MintableTokenInterface public token; // The token being sold
uint public tokenDecimals; // Token decimals
mapping (address => TokenInterface) public allowedTokens;
// allowed tokens list
mapping (address => uint) public tokensValues;
// TOKEN to ETH conversion rate (oraclized)
uint public startTime; // start and end timestamps where
uint public endTime; // investments are allowed (both inclusive)
address public wallet; // address where funds are collected
uint public price; // how many token (1 * 10 ** decimals) a buyer gets per wei
uint public hardCap;
uint public softCap;
address public extraTokensHolder; // address to mint/transfer extra tokens (0 – 0%, 1000 - 100.0%)
uint public extraDistributionPart; // % of extra distribution
// ███████╗████████╗ █████╗ ████████╗███████╗
// ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝
// ███████╗ ██║ ███████║ ██║ █████╗
// ╚════██║ ██║ ██╔══██║ ██║ ██╔══╝
// ███████║ ██║ ██║ ██║ ██║ ███████╗
// ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝
// amount of raised money in wei
uint public weiRaised;
// Current crowdsale state
State public state;
// Temporal balances to pull tokens after token sale
// requires to ship required balance to smart contract
mapping (address => uint) public beneficiaryInvest;
uint public soldTokens;
mapping (address => uint) public weiDeposit;
mapping (address => mapping(address => uint)) public altDeposit;
modifier inState(State _target) {
require(state == _target);
_;
}
// ███████╗██╗ ██╗███████╗███╗ ██╗████████╗███████╗
// ██╔════╝██║ ██║██╔════╝████╗ ██║╚══██╔══╝██╔════╝
// █████╗ ██║ ██║█████╗ ██╔██╗ ██║ ██║ ███████╗
// ██╔══╝ ╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ╚════██║
// ███████╗ ╚████╔╝ ███████╗██║ ╚████║ ██║ ███████║
// ╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝
event EthBuy(
address indexed purchaser,
address indexed beneficiary,
uint value,
uint amount);
event HashBuy(
address indexed beneficiary,
uint value,
uint amount,
uint timestamp,
bytes32 indexed bitcoinHash);
event AltBuy(
address indexed beneficiary,
address indexed allowedToken,
uint allowedTokenValue,
uint ethValue,
uint shipAmount);
event ShipTokens(address indexed owner, uint amount);
event Sanetize();
event Finalize();
event Whitelisted(address indexed beneficiary, uint min, uint max);
event PersonalBonus(address indexed beneficiary, address indexed referer, uint bonus, uint refererBonus);
event FundsClaimed(address indexed owner, uint amount);
// ███████╗███████╗████████╗██╗ ██╗██████╗ ███╗ ███╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ███████╗
// ██╔════╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ████╗ ████║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██╔════╝
// ███████╗█████╗ ██║ ██║ ██║██████╔╝ ██╔████╔██║█████╗ ██║ ███████║██║ ██║██║ ██║███████╗
// ╚════██║██╔══╝ ██║ ██║ ██║██╔═══╝ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║██║ ██║██║ ██║╚════██║
// ███████║███████╗ ██║ ╚██████╔╝██║ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║╚██████╔╝██████╔╝███████║
// ╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
function setFlags(
// Should be whitelisted to buy tokens
bool _isWhitelisted,
// Should be known user to buy tokens
bool _isKnownOnly,
// Enable amount bonuses in crowdsale?
bool _isAmountBonus,
// Enable early bird bonus in crowdsale?
bool _isEarlyBonus,
// Allow to buy tokens for another tokens?
bool _isTokenExchange,
// Allow to issue tokens with tx hash (ex bitcoin)
bool _isAllowToIssue,
// Should reject purchases with Ether?
bool _isDisableEther,
// Should mint extra tokens for future distribution?
bool _isExtraDistribution,
// Will ship token via minting?
bool _isTransferShipment,
// Should be capped in ether
bool _isCappedInEther,
// Should beneficiaries pull their tokens?
bool _isPersonalBonuses,
// Should allow to claim funds before finalization?
bool _isAllowClaimBeforeFinalization)
inState(State.Setup) onlyOwner public
{
isWhitelisted = _isWhitelisted;
isKnownOnly = _isKnownOnly;
isAmountBonus = _isAmountBonus;
isEarlyBonus = _isEarlyBonus;
isTokenExchange = _isTokenExchange;
isAllowToIssue = _isAllowToIssue;
isDisableEther = _isDisableEther;
isExtraDistribution = _isExtraDistribution;
isTransferShipment = _isTransferShipment;
isCappedInEther = _isCappedInEther;
isPersonalBonuses = _isPersonalBonuses;
isAllowClaimBeforeFinalization = _isAllowClaimBeforeFinalization;
}
// ! Could be changed in process of sale (since 02.2018)
function setMinimum(uint _amount, bool _inToken)
onlyOwner public
{
if (_amount == 0) {
isMinimumValue = false;
minimumPurchaseValue = 0;
} else {
isMinimumValue = true;
isMinimumInEther = !_inToken;
minimumPurchaseValue = _amount;
}
}
function setPrice(uint _price)
inState(State.Setup) onlyOwner public
{
require(_price > 0);
price = _price;
}
function setSoftHardCaps(uint _softCap, uint _hardCap)
inState(State.Setup) onlyOwner public
{
hardCap = _hardCap;
softCap = _softCap;
}
function setTime(uint _start, uint _end)
inState(State.Setup) onlyOwner public
{
require(_start < _end);
require(_end > block.timestamp);
startTime = _start;
endTime = _end;
}
function setToken(address _tokenAddress)
inState(State.Setup) onlyOwner public
{
token = MintableTokenInterface(_tokenAddress);
tokenDecimals = token.decimals();
}
function setWallet(address _wallet)
inState(State.Setup) onlyOwner public
{
require(_wallet != address(0));
wallet = _wallet;
}
function setRegistry(address _registry)
inState(State.Setup) onlyOwner public
{
require(_registry != address(0));
userRegistry = UserRegistryInterface(_registry);
}
function setExtraDistribution(address _holder, uint _extraPart)
inState(State.Setup) onlyOwner public
{
require(_holder != address(0));
extraTokensHolder = _holder;
extraDistributionPart = _extraPart;
}
function setAmountBonuses(uint[] _amountSlices, uint[] _bonuses)
inState(State.Setup) onlyOwner public
{
require(_amountSlices.length > 1);
require(_bonuses.length == _amountSlices.length);
uint lastSlice = 0;
for (uint index = 0; index < _amountSlices.length; index++) {
require(_amountSlices[index] > lastSlice);
lastSlice = _amountSlices[index];
amountSlices.push(lastSlice);
amountBonuses[lastSlice] = _bonuses[index];
}
amountSlicesCount = amountSlices.length;
}
function setTimeBonuses(uint[] _timeSlices, uint[] _bonuses)
// ! Not need to check state since changes at 02.2018
// inState(State.Setup)
onlyOwner
public
{
// Only once in life time
// ! Time bonuses is changable after 02.2018
// require(timeSlicesCount == 0);
require(_timeSlices.length > 0);
require(_bonuses.length == _timeSlices.length);
uint lastSlice = 0;
uint lastBonus = 10000;
if (timeSlicesCount > 0) {
// ! Since time bonuses is changable we should take latest first
lastSlice = timeSlices[timeSlicesCount - 1];
lastBonus = timeBonuses[lastSlice];
}
for (uint index = 0; index < _timeSlices.length; index++) {
require(_timeSlices[index] > lastSlice);
// ! Add check for next bonus is equal or less than previous
require(_bonuses[index] <= lastBonus);
// ? Should we check bonus in a future
lastSlice = _timeSlices[index];
timeSlices.push(lastSlice);
timeBonuses[lastSlice] = _bonuses[index];
}
timeSlicesCount = timeSlices.length;
}
function setTokenExcange(address _token, uint _value)
inState(State.Setup) onlyOwner public
{
allowedTokens[_token] = TokenInterface(_token);
updateTokenValue(_token, _value);
}
function saneIt()
inState(State.Setup) onlyOwner public
{
require(startTime < endTime);
require(endTime > now);
require(price > 0);
require(wallet != address(0));
require(token != address(0));
if (isKnownOnly) {
require(userRegistry != address(0));
}
if (isAmountBonus) {
require(amountSlicesCount > 0);
}
if (isExtraDistribution) {
require(extraTokensHolder != address(0));
}
if (isTransferShipment) {
require(token.balanceOf(address(this)) >= hardCap);
} else {
require(token.owner() == address(this));
}
state = State.Active;
}
function finalizeIt(address _futureOwner) inState(State.Active) onlyOwner public {
require(ended());
token.transferOwnership(_futureOwner);
if (success()) {
state = State.Claim;
} else {
state = State.Refund;
}
}
function historyIt() inState(State.Claim) onlyOwner public {
require(address(this).balance == 0);
state = State.History;
}
// ███████╗██╗ ██╗███████╗ ██████╗██╗ ██╗████████╗███████╗
// ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ ██║╚══██╔══╝██╔════╝
// █████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ ██║ █████╗
// ██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██║ ██╔══╝
// ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝ ██║ ███████╗
// ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝
function calculateEthAmount(
address _beneficiary,
uint _weiAmount,
uint _time,
uint _totalSupply
) public constant returns(
uint calculatedTotal,
uint calculatedBeneficiary,
uint calculatedExtra,
uint calculatedreferer,
address refererAddress)
{
_totalSupply;
uint bonus = 0;
if (isAmountBonus) {
bonus = bonus.add(calculateAmountBonus(_weiAmount));
}
if (isEarlyBonus) {
bonus = bonus.add(calculateTimeBonus(_time.sub(startTime)));
}
if (isPersonalBonuses && personalBonuses[_beneficiary].bonus > 0) {
bonus = bonus.add(personalBonuses[_beneficiary].bonus);
}
calculatedBeneficiary = _weiAmount.mul(10 ** tokenDecimals).div(price);
if (bonus > 0) {
calculatedBeneficiary = calculatedBeneficiary.add(calculatedBeneficiary.mul(bonus).div(10000));
}
if (isExtraDistribution) {
calculatedExtra = calculatedBeneficiary.mul(extraDistributionPart).div(10000);
}
if (isPersonalBonuses &&
personalBonuses[_beneficiary].refererAddress != address(0) &&
personalBonuses[_beneficiary].refererBonus > 0)
{
calculatedreferer = calculatedBeneficiary.mul(personalBonuses[_beneficiary].refererBonus).div(10000);
refererAddress = personalBonuses[_beneficiary].refererAddress;
}
calculatedTotal = calculatedBeneficiary.add(calculatedExtra).add(calculatedreferer);
}
function calculateAmountBonus(uint _changeAmount) public constant returns(uint) {
uint bonus = 0;
for (uint index = 0; index < amountSlices.length; index++) {
if(amountSlices[index] > _changeAmount) {
break;
}
bonus = amountBonuses[amountSlices[index]];
}
return bonus;
}
function calculateTimeBonus(uint _at) public constant returns(uint) {
uint bonus = 0;
for (uint index = timeSlices.length; index > 0; index--) {
if(timeSlices[index - 1] < _at) {
break;
}
bonus = timeBonuses[timeSlices[index - 1]];
}
return bonus;
}
function validPurchase(
address _beneficiary,
uint _weiAmount,
uint _tokenAmount,
uint _extraAmount,
uint _totalAmount,
uint _time)
public constant returns(bool)
{
_tokenAmount;
_extraAmount;
// ! Check min purchase value (since 02.2018)
if (isMinimumValue) {
// ! Check min purchase value in ether (since 02.2018)
if (isMinimumInEther && _weiAmount < minimumPurchaseValue) {
return false;
}
// ! Check min purchase value in tokens (since 02.2018)
if (!isMinimumInEther && _tokenAmount < minimumPurchaseValue) {
return false;
}
}
if (_time < startTime || _time > endTime) {
return false;
}
if (isKnownOnly && !userRegistry.knownAddress(_beneficiary)) {
return false;
}
uint finalBeneficiaryInvest = beneficiaryInvest[_beneficiary].add(_weiAmount);
uint finalTotalSupply = soldTokens.add(_totalAmount);
if (isWhitelisted) {
WhitelistRecord storage record = whitelist[_beneficiary];
if (!record.allow ||
record.min > finalBeneficiaryInvest ||
record.max < finalBeneficiaryInvest) {
return false;
}
}
if (isCappedInEther) {
if (weiRaised.add(_weiAmount) > hardCap) {
return false;
}
} else {
if (finalTotalSupply > hardCap) {
return false;
}
}
return true;
}
function updateTokenValue(address _token, uint _value) onlyOwner public {
require(address(allowedTokens[_token]) != address(0x0));
tokensValues[_token] = _value;
}
// ██████╗ ███████╗ █████╗ ██████╗
// ██╔══██╗██╔════╝██╔══██╗██╔══██╗
// ██████╔╝█████╗ ███████║██║ ██║
// ██╔══██╗██╔══╝ ██╔══██║██║ ██║
// ██║ ██║███████╗██║ ██║██████╔╝
// ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝
function success() public constant returns(bool) {
if (isCappedInEther) {
return weiRaised >= softCap;
} else {
return token.totalSupply() >= softCap;
}
}
function capped() public constant returns(bool) {
if (isCappedInEther) {
return weiRaised >= hardCap;
} else {
return token.totalSupply() >= hardCap;
}
}
function ended() public constant returns(bool) {
return capped() || block.timestamp >= endTime;
}
// ██████╗ ██╗ ██╗████████╗███████╗██╗██████╗ ███████╗
// ██╔═══██╗██║ ██║╚══██╔══╝██╔════╝██║██╔══██╗██╔════╝
// ██║ ██║██║ ██║ ██║ ███████╗██║██║ ██║█████╗
// ██║ ██║██║ ██║ ██║ ╚════██║██║██║ ██║██╔══╝
// ╚██████╔╝╚██████╔╝ ██║ ███████║██║██████╔╝███████╗
// ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝╚═════╝ ╚══════╝
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) inState(State.Active) public payable {
require(!isDisableEther);
uint shipAmount = sellTokens(_beneficiary, msg.value, block.timestamp);
require(shipAmount > 0);
forwardEther();
}
function buyWithHash(address _beneficiary, uint _value, uint _timestamp, bytes32 _hash)
inState(State.Active) onlyOwner public
{
require(isAllowToIssue);
uint shipAmount = sellTokens(_beneficiary, _value, _timestamp);
require(shipAmount > 0);
HashBuy(_beneficiary, _value, shipAmount, _timestamp, _hash);
}
function receiveApproval(address _from,
uint256 _value,
address _token,
bytes _extraData) public
{
if (_token == address(token)) {
TokenInterface(_token).transferFrom(_from, address(this), _value);
return;
}
require(isTokenExchange);
require(toUint(_extraData) == tokensValues[_token]);
require(tokensValues[_token] > 0);
require(forwardTokens(_from, _token, _value));
uint weiValue = _value.mul(tokensValues[_token]).div(10 ** allowedTokens[_token].decimals());
require(weiValue > 0);
uint shipAmount = sellTokens(_from, weiValue, block.timestamp);
require(shipAmount > 0);
AltBuy(_from, _token, _value, weiValue, shipAmount);
}
function claimFunds() onlyOwner public returns(bool) {
require(state == State.Claim || (isAllowClaimBeforeFinalization && success()));
wallet.transfer(address(this).balance);
return true;
}
function claimTokenFunds(address _token) onlyOwner public returns(bool) {
require(state == State.Claim || (isAllowClaimBeforeFinalization && success()));
uint balance = allowedTokens[_token].balanceOf(address(this));
require(balance > 0);
require(allowedTokens[_token].transfer(wallet, balance));
return true;
}
function claimRefundEther(address _beneficiary) inState(State.Refund) public returns(bool) {
require(weiDeposit[_beneficiary] > 0);
_beneficiary.transfer(weiDeposit[_beneficiary]);
return true;
}
function claimRefundTokens(address _beneficiary, address _token) inState(State.Refund) public returns(bool) {
require(altDeposit[_token][_beneficiary] > 0);
require(allowedTokens[_token].transfer(_beneficiary, altDeposit[_token][_beneficiary]));
return true;
}
function addToWhitelist(address _beneficiary, uint _min, uint _max) onlyOwner public
{
require(_beneficiary != address(0));
require(_min <= _max);
if (_max == 0) {
_max = 10 ** 40; // should be huge enough? :0
}
whitelist[_beneficiary] = WhitelistRecord(true, _min, _max);
Whitelisted(_beneficiary, _min, _max);
}
function setPersonalBonus(
address _beneficiary,
uint _bonus,
address _refererAddress,
uint _refererBonus) onlyOwner public {
personalBonuses[_beneficiary] = PersonalBonusRecord(
_bonus,
_refererAddress,
_refererBonus
);
PersonalBonus(_beneficiary, _refererAddress, _bonus, _refererBonus);
}
// ██╗███╗ ██╗████████╗███████╗██████╗ ███╗ ██╗ █████╗ ██╗ ███████╗
// ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗████╗ ██║██╔══██╗██║ ██╔════╝
// ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝██╔██╗ ██║███████║██║ ███████╗
// ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗██║╚██╗██║██╔══██║██║ ╚════██║
// ██║██║ ╚████║ ██║ ███████╗██║ ██║██║ ╚████║██║ ██║███████╗███████║
// ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚══════╝
// low level token purchase function
function sellTokens(address _beneficiary, uint _weiAmount, uint timestamp)
inState(State.Active) internal returns(uint)
{
uint beneficiaryTokens;
uint extraTokens;
uint totalTokens;
uint refererTokens;
address refererAddress;
(totalTokens, beneficiaryTokens, extraTokens, refererTokens, refererAddress) = calculateEthAmount(
_beneficiary,
_weiAmount,
timestamp,
token.totalSupply());
require(validPurchase(_beneficiary, // Check if current purchase is valid
_weiAmount,
beneficiaryTokens,
extraTokens,
totalTokens,
timestamp));
weiRaised = weiRaised.add(_weiAmount); // update state (wei amount)
beneficiaryInvest[_beneficiary] = beneficiaryInvest[_beneficiary].add(_weiAmount);
shipTokens(_beneficiary, beneficiaryTokens); // ship tokens to beneficiary
EthBuy(msg.sender, // Fire purchase event
_beneficiary,
_weiAmount,
beneficiaryTokens);
ShipTokens(_beneficiary, beneficiaryTokens);
if (isExtraDistribution) { // calculate and
shipTokens(extraTokensHolder, extraTokens);
ShipTokens(extraTokensHolder, extraTokens);
}
if (isPersonalBonuses) {
PersonalBonusRecord storage record = personalBonuses[_beneficiary];
if (record.refererAddress != address(0) && record.refererBonus > 0) {
shipTokens(record.refererAddress, refererTokens);
ShipTokens(record.refererAddress, refererTokens);
}
}
soldTokens = soldTokens.add(totalTokens);
return beneficiaryTokens;
}
function shipTokens(address _beneficiary, uint _amount)
inState(State.Active) internal
{
if (isTransferShipment) {
token.transfer(_beneficiary, _amount);
} else {
token.mint(address(this), _amount);
token.transfer(_beneficiary, _amount);
}
}
function forwardEther() internal returns (bool) {
weiDeposit[msg.sender] = msg.value;
return true;
}
function forwardTokens(address _beneficiary, address _tokenAddress, uint _amount) internal returns (bool) {
TokenInterface allowedToken = allowedTokens[_tokenAddress];
allowedToken.transferFrom(_beneficiary, address(this), _amount);
altDeposit[_tokenAddress][_beneficiary] = _amount;
return true;
}
// ██╗ ██╗████████╗██╗██╗ ███████╗
// ██║ ██║╚══██╔══╝██║██║ ██╔════╝
// ██║ ██║ ██║ ██║██║ ███████╗
// ██║ ██║ ██║ ██║██║ ╚════██║
// ╚██████╔╝ ██║ ██║███████╗███████║
// ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝
function toUint(bytes left) public pure returns (uint) {
uint out;
for (uint i = 0; i < 32; i++) {
out |= uint(left[i]) << (31 * 8 - i * 8);
}
return out;
}
}
contract BaseAltCrowdsale is Crowdsale {
function BaseAltCrowdsale(
address _registry,
address _token,
address _extraTokensHolder,
address _wallet,
bool _isWhitelisted,
uint _price,
uint _start,
uint _end,
uint _softCap,
uint _hardCap
) public {
setFlags(
// Should be whitelisted to buy tokens
// _isWhitelisted,
_isWhitelisted,
// Should be known user to buy tokens
// _isKnownOnly,
true,
// Enable amount bonuses in crowdsale?
// _isAmountBonus,
true,
// Enable early bird bonus in crowdsale?
// _isEarlyBonus,
true,
// Allow to buy tokens for another tokens?
// _isTokenExcange,
false,
// Allow to issue tokens with tx hash (ex bitcoin)
// _isAllowToIssue,
true,
// Should reject purchases with Ether?
// _isDisableEther,
false,
// Should mint extra tokens for future distribution?
// _isExtraDistribution,
true,
// Will ship token via minting?
// _isTransferShipment,
false,
// Should be capped in ether
// bool _isCappedInEther,
true,
// Should check personal bonuses?
// _isPersonalBonuses
true,
// Should allow to claimFunds before finalizations?
false
);
setToken(_token);
setTime(_start, _end);
setRegistry(_registry);
setWallet(_wallet);
setExtraDistribution(
_extraTokensHolder,
6667 // 66.67%
);
setSoftHardCaps(
_softCap, // soft
_hardCap // hard
);
// 200 ALT per 1 ETH
setPrice(_price);
}
}
contract AltCrowdsalePhaseOne is BaseAltCrowdsale {
function AltCrowdsalePhaseOne (
address _registry,
address _token,
address _extraTokensHolder,
address _wallet
)
BaseAltCrowdsale(
_registry,
_token,
_extraTokensHolder,
_wallet,
// Whitelisted
false,
// price 1 ETH -> 100000 ALT
uint(1 ether).div(100000),
// start - 13 Apr 2018 12:18:33 GMT
1523621913,
// end - 30 Jun 2018 23:59:59 GMT
1530403199,
// _softCap,
2500 ether,
// _hardCap
7500 ether
)
public {
}
}
|
! Not need to check state since changes at 02.2018 inState(State.Setup) Only once in life time ! Time bonuses is changable after 02.2018 require(timeSlicesCount == 0); ! Since time bonuses is changable we should take latest first ! Add check for next bonus is equal or less than previous ? Should we check bonus in a future
|
function setTimeBonuses(uint[] _timeSlices, uint[] _bonuses)
onlyOwner
public
{
require(_timeSlices.length > 0);
require(_bonuses.length == _timeSlices.length);
uint lastSlice = 0;
uint lastBonus = 10000;
if (timeSlicesCount > 0) {
lastSlice = timeSlices[timeSlicesCount - 1];
lastBonus = timeBonuses[lastSlice];
}
for (uint index = 0; index < _timeSlices.length; index++) {
require(_timeSlices[index] > lastSlice);
require(_bonuses[index] <= lastBonus);
lastSlice = _timeSlices[index];
timeSlices.push(lastSlice);
timeBonuses[lastSlice] = _bonuses[index];
}
timeSlicesCount = timeSlices.length;
}
| 615,184 |
pragma ton-solidity ^0.37.0;
pragma AbiHeader expire;
pragma AbiHeader time;
pragma AbiHeader pubkey;
import "./Auction.sol";
import "./Certificate.sol";
import "./interfaces/IRootAuction.sol";
import "./interfaces/IRootManagement.sol";
import "./utils/Stash.sol";
import "./interfaces/IRoot.sol";
/**
* ██████╗ ███╗ ██╗███████╗
* ██╔══██╗███████╗████╗ ██║██╔════╝
* ██║ ██║██▄▄▄██║██╔██╗ ██║███████╗
* ██║ ██║██╔════╝██║╚██╗██║╚════██║
* ██████╔╝███████╗██║ ╚████║███████║
* ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝
* Decentralized Name Service
*
* Error codes
* 100 - Method for the owner only
* 101 - Method for the manager only
* 102 - Manager address cannot be null
* 103 - Invalid name
* 104 - Method available with only 1 ton
* 105 - Invalid number of periods
* 106 - Certificate only method
* 107 - Auction only method
* 108 - Too early to create an auction
*
* 200 - Hash doesn't exist
* 201 - Hash received from the wrong address
*/
contract Root is Stash, IRoot, IRootManagement, IRootAuction {
/*************
* CONSTANTS *
*************/
uint256 private constant DEFAULT = 0x0000111122223333444455556666777788889999AAAABBBBCCCCDDDDEEEEFFFF;
/*************
* VARIABLES *
*************/
TvmCell private _certificateCode;
uint32 private _certificateDuration;
uint32 private _certificateProlongationPeriod;
uint32 private _certificateAuctionPeriod;
bool private _certificateCheckLeapYear;
TvmCell private _auctionCode;
uint32 private _auctionBidsDuration;
uint32 private _auctionSubmittingDuration;
uint32 private _auctionFinishDuration;
address private _manager;
uint32[] private _versionHistory;
/*************
* MODIFIERS *
*************/
modifier accept {
tvm.accept();
_;
}
modifier onlyOwner {
require(msg.pubkey() == tvm.pubkey(), 100, "Method for the owner only");
_;
}
modifier onlyManager {
require(msg.sender == _manager, 101, "Method for the manager only");
_;
}
modifier managerIsNotNull(address manager) {
require(manager != address(0), 102, "Manager address cannot be null");
_;
}
modifier nameIsValid(string name) {
require(_nameIsValid(name), 103, "Invalid name");
_;
}
modifier oneTon() {
require(msg.value == 1 ton, 104, "Method available with only 1 ton");
_;
}
modifier periodsIsValid(uint8 periods) {
require(periods >= 1 && periods <= 4, 105, "Invalid number of periods");
_;
}
modifier onlyCertificate(string name) {
require(msg.sender == resolve(name), 106, "Certificate only method");
_;
}
modifier onlyAuction(string name) {
require(msg.sender == resolveAuction(name), 107, "Auction only method");
_;
}
modifier canBePutUpForAuction(uint32 expirationTime) {
require(now >= (int256(expirationTime) - _certificateAuctionPeriod), 108, "Too early to create an auction");
_;
}
/***************
* CONSTRUCTOR *
***************/
/**
* certificateCode ............... Code of certificate.
* certificateDuration ........... Minimum period duration in seconds for which the certificate is issued.
* certificateProlongationPeriod . Duration of the period in seconds,
* during which the owner can prolong the certificate..
* certificateAuctionPeriod ...... Length of the period in seconds, before the certificate expires,
* during which someone can create an auction.
* certificateCheckLeapYear ...... If true, adds a day to certificate expiration date in leap year.
* auctionCode ................... Code of auction.
* auctionBidsDuration ........... The minimum duration of the auction in seconds.
* auctionSubmittingDuration ..... Duration of period, in seconds, during which users can pay value.
* auctionFinishDuration ......... Duration of period, in seconds, during which users can complete auction.
* manager ....................... Contract that governs this contract.
* names ......................... UTF8-encoded names.
*/
constructor(
TvmCell certificateCode,
uint32 certificateDuration,
uint32 certificateProlongationPeriod,
uint32 certificateAuctionPeriod,
bool certificateCheckLeapYear,
TvmCell auctionCode,
uint32 auctionBidsDuration,
uint32 auctionSubmittingDuration,
uint32 auctionFinishDuration,
address manager,
string[] names
)
public onlyOwner managerIsNotNull(manager) accept
{
_certificateCode = certificateCode;
_certificateDuration = certificateDuration;
_certificateProlongationPeriod = certificateProlongationPeriod;
_certificateAuctionPeriod = certificateAuctionPeriod;
_certificateCheckLeapYear = certificateCheckLeapYear;
_auctionCode = auctionCode;
_auctionBidsDuration = auctionBidsDuration;
_auctionSubmittingDuration = auctionSubmittingDuration;
_auctionFinishDuration = auctionFinishDuration;
_manager = manager;
if (_namesIsValid(names))
_deployDefinedCertificates(names);
_versionHistory.push(now);
}
/***************************
* EXTERNAL * ONLY MANAGER *
***************************/
/**
* Manager can change manager address to another.
* manager . contract that governs this contract.
*/
function changeManager(address manager) external override onlyManager managerIsNotNull(manager) accept {
_manager = manager;
}
/**
* Manager can upgrade auction code.
* code . New version of contract code.
*/
function upgrade(TvmCell code) external override onlyManager accept {
tvm.setcode(code);
tvm.setCurrentCode(code);
onCodeUpgrade();
}
/**
* Manager can create new certificate bypassing an auction.
* name ........... Name of the certificate.
* expirationTime . Expiration time of the certificate. Unix timestamp in seconds.
* price .......... Price of the certificate. Used for prolongation.
*/
function createCertificate(string name, uint32 expirationTime, uint128 price)
external
override
onlyManager
accept
nameIsValid(name)
{
_deployCertificate(name, msg.sender, DEFAULT, expirationTime, price);
}
/**
* Manager can prolong certificate which were created by the manager.
* name ........... Name of the certificate.
* expirationTime . Expiration time of the certificate. Unix timestamp in seconds.
*/
function prolongCertificate(string name, uint32 expirationTime) external override onlyManager accept {
address certificateAddress = resolve(name);
Certificate(certificateAddress).prolong(expirationTime);
}
/***************************
* EXTERNAL * ONLY AUCTION *
***************************/
function auctionComplete(
string name,
uint8 periods,
address addr,
uint128 price,
bool needToCreate
)
external override onlyAuction(name)
{
if (needToCreate)
_deployCertificate(name, addr, DEFAULT, periods * _certificateDuration, price);
else {
address certificateAddress = resolve(name);
Certificate(certificateAddress).renew(addr, DEFAULT, periods * _certificateDuration, price);
}
}
/**********
* PUBLIC *
**********/
/**
* Anyone can register a certificate.
* name .... Name of the certificate.
* periods . The number of periods for which the certificate is registered. Minimum is 0, maximum is 4.
* The duration of the period is determined by the parameters:
* _certificateDuration and _certificateCheckLeapYear.
* bid ..... Hash of bid. tvm.hash(uint128 value, uint256 salt)
*/
function registerName(
string name,
uint8 periods,
uint256 bid
)
public oneTon nameIsValid(name) periodsIsValid(periods)
{
address certificateAddress = resolve(name);
uint128 hash = _stash(certificateAddress, msg.sender, name, periods, bid);
Certificate(certificateAddress).receiveRegistrationInfo{
value: 0,
bounce: true,
flag: 64,
callback: onReceiveRegistrationInfo
}(
hash
);
}
////////////////////////////////////////////////////
// Certificate.receiveRegistrationInfo() onBounce //
////////////////////////////////////////////////////
onBounce(TvmSlice slice) external {
uint32 functionId = slice.decode(uint32);
if (functionId == tvm.functionId(Certificate.receiveRegistrationInfo)) {
slice.decode(uint32);
uint128 hash = slice.decode(uint128);
onReceiveRegistrationInfo(hash, 0);
}
}
////////////////////////////////////////////////////
// Certificate.receiveRegistrationInfo() callback //
////////////////////////////////////////////////////
function onReceiveRegistrationInfo(uint128 rHash, uint32 expirationTime)
public
hashExists(rHash)
validHashSource(rHash)
canBePutUpForAuction(expirationTime)
{
AuctionParameters parameters = _unpack(rHash);
//////////////////////////////////////////////////////////////////////////////////////
// Deployment. If the auction has already deployed, the transaction will be aborted //
//////////////////////////////////////////////////////////////////////////////////////
address auctionAddress = new Auction{
code: _auctionCode,
value: 0.2 ton,
pubkey: tvm.pubkey(),
varInit: {
_name: parameters.name,
_root: address(this)
}
}(_auctionBidsDuration, _auctionSubmittingDuration, _auctionFinishDuration);
//////////////////////////////////////////////////////////////////////////////////////////////
// If the auction has already started and has not finished, the transaction will be aborted //
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// If number of periods is not equal to the number of auction periods, the transaction will be aborted //
/////////////////////////////////////////////////////////////////////////////////////////////////////////
Auction(auctionAddress).bid{value: 0.6 ton}(
parameters.sender,
parameters.periods,
parameters.bid,
expirationTime > 0
);
}
/***********
* GETTERS *
***********/
function getSettings()
public
view
returns (
TvmCell certificateCode,
uint32 certificateDuration,
uint32 certificateProlongationPeriod,
uint32 certificateAuctionPeriod,
bool certificateCheckLeapYear,
TvmCell auctionCode,
uint32 auctionBidsDuration,
uint32 auctionSubmittingDuration,
uint32 auctionFinishDuration
)
{
return (
_certificateCode,
_certificateDuration,
_certificateProlongationPeriod,
_certificateAuctionPeriod,
_certificateCheckLeapYear,
_auctionCode,
_auctionBidsDuration,
_auctionSubmittingDuration,
_auctionFinishDuration
);
}
function getPublicKey() public view returns (uint256 publicKey) {
return tvm.pubkey();
}
function getManager() public view returns (address manager) {
return _manager;
}
function getVersionHistory() public view returns (uint32[] versionHistory) {
return _versionHistory;
}
function resolve(string name) override public view returns (address addr) {
TvmCell stateInit = tvm.buildStateInit({
contr: Certificate,
varInit: {
_name: name,
_root: address(this)
},
pubkey: tvm.pubkey(),
code: _certificateCode
});
return address(tvm.hash(stateInit));
}
function resolveAuction(string name) override public view returns (address addr) {
TvmCell stateInit = tvm.buildStateInit({
contr: Auction,
varInit: {
_name: name,
_root: address(this)
},
pubkey: tvm.pubkey(),
code: _auctionCode
});
return address(tvm.hash(stateInit));
}
/***********
* PRIVATE *
***********/
/**
* Called once and prevents the constructor from being called with an unpredictable result.
* Returns false if name length == 0 or name length > 255 or name contains invalid characters.
* Examples:
* _validateLengths(['', '1234']) // false
* _validateLengths(['.', '1234']) // false
* _validateLengths(['/', '1234']) // false
* _validateLengths(['1234', '5']) // true
*/
function _namesIsValid(string[] names) private pure returns (bool) {
for (uint8 i = 0; i < names.length; i++)
if (!_nameIsValid(names[i]))
return false;
return true;
}
/**
* Returns true if string contains any UTF-8 encoded string except for a dot "." and forward slash "/".
* Examples:
* _validateCharacters('1.34') // false
* _validateCharacters('1/34') // false
* _validateCharacters('1234') // true
*/
function _nameIsValid(string name) private pure returns (bool) {
if (name.byteLength() < 1 || name.byteLength() > 0xFF)
return false;
TvmSlice slice = name.toSlice();
uint16 bytesCount;
uint8 character;
bool runAgain;
do {
bytesCount = slice.bits() >> 3;
for (uint8 i = 0; i < bytesCount; i++) {
character = slice.decode(uint8);
if (
character == 0x2E || // "."
character == 0x2F // "/"
)
return false;
}
if (slice.refs() > 0)
slice = slice.loadRef().toSlice();
else
runAgain = false;
} while(runAgain);
return true;
}
function _deployDefinedCertificates(string[] names) private {
address manager = _manager;
for (uint16 i = 0; i < names.length; i++)
_deployCertificate(names[i], manager, DEFAULT, 0xFFFFFFFF, 0);
}
function _deployCertificate(
string name,
address manager,
uint256 owner,
uint32 expirationTime,
uint128 price
)
private
{
new Certificate{
code: _certificateCode,
value: 0.4 ton,
pubkey: tvm.pubkey(),
varInit: {
_name: name,
_root: address(this)
}
}(manager,owner, expirationTime, price);
}
/*****************************
* PRIVATE * ON CODE UPGRADE *
*****************************/
function onCodeUpgrade() private pure {}
}
|
Manager can prolong certificate which were created by the manager. name ........... Name of the certificate. expirationTime . Expiration time of the certificate. Unix timestamp in seconds./
|
function prolongCertificate(string name, uint32 expirationTime) external override onlyManager accept {
address certificateAddress = resolve(name);
Certificate(certificateAddress).prolong(expirationTime);
}
| 6,382,713 |
pragma solidity ^0.4.18;
/**
* @title ERC20
*
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address who) 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 allowance(address owner, address spender) public view returns (uint256);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable && Mintable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* @dev Added mintOwner address how controls the minting
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public mintOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event MintOwnershipTransferred(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;
mintOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyMintOwner() {
require(msg.sender == mintOwner);
_;
}
/**
* @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;
}
/**
* @dev Allows the current owner to transfer mint control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferMintOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit MintOwnershipTransferred(mintOwner, newOwner);
mintOwner = newOwner;
}
}
/**
*
* @title Edge token
* An ERC-20 token designed specifically for crowdsales with investor protection and further development path.
*
*
*/
contract EdgeToken is ERC20, Ownable {
using SafeMath for uint256;
//Balances
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) internal allowed;
//Minting
event Mint(address indexed to, uint256 amount);
event MintFinished();
//If token is mintable
bool public mintingFinished = false;
//Total supply of tokens
uint256 totalSupply_ = 0;
//Hardcap is 1,000,000,000 - One billion tokens
uint256 hardCap_ = 1000000000000000000000000000;
//Constructor
constructor() public {
}
//Fix for the ERC20 short address attack.
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev allowed total number of tokens
*/
function hardCap() public view returns (uint256) {
return hardCap_;
}
/**
* @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 onlyPayloadSize(2 * 32) returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/**
* @dev Internal transfer, only can be called by this contract
* @param _from is msg.sender 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 returns (bool){
require(_to != address(0)); // Prevent transfer to 0x0 address.
require(_value <= balances[msg.sender]); // Check if the sender has enough
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require(_value <= balances[_from]); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check if the sender is allowed to send
// SafeMath.sub will throw if there is not enough balance.
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 Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @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 spend.
*
* 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;
}
/**
* MintableToken functionality
*/
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMintOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= hardCap_);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Owner can transfer other tokens that are sent here by mistake
*
*/
function refundOtherTokens(address _recipient, ERC20 _token) public onlyOwner {
require(_token != this);
uint256 balance = _token.balanceOf(this);
require(_token.transfer(_recipient, balance));
}
}
/**
* @title EDGE token EDGE
*
*/
contract EToken is EdgeToken {
string public constant name = "We Got Edge Token";
string public constant symbol = "EDGE";
uint8 public constant decimals = 18;
}
|
allowed total number of tokens/
|
function hardCap() public view returns (uint256) {
return hardCap_;
}
| 640,676 |
pragma solidity ^0.4.20;
contract POMDA {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "POMDA";
string public symbol = "POMDA";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 20 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function POMDA()
public
{
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
//require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
// antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
Return the buy price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
|
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
| 7,835,018 |
./partial_match/1/0xCDb49e21b5C3D6D2a38a648CeB97fBFaBbF15832/sources/OXOProject.sol
|
ERC20 interface/
|
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
pragma solidity ^0.5.2;
}
| 4,178,172 |
./partial_match/4/0x621D11eBb33CaCEb38DDA967F1E33973563B6977/sources/DEFIBaseToken.sol
|
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;
}
| 8,546,508 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// File: @openzeppelin/contracts/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/cat/main.sol
pragma solidity ^0.8.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 MaineCoonToken is IERC20, Context {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor () {
_mint(address(0x6a155A55d40739Bd48a80C626bcdDd69018a835f), 22222222222 * 1e18);
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return "Maine Coon";
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return "MAIN";
}
/**
* @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 this function is
* overloaded;
*
* 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 18;
}
/**
* @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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
_afterTokenTransfer(sender, recipient, 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
_afterTokenTransfer(account, address(0), 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 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 { }
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
|
Returns the name of the token./
|
function name() public view virtual returns (string memory) {
return "Maine Coon";
}
| 322,347 |
./partial_match/1/0x5d885910F7631deE8567f589eB1a81DfaE80ae7C/sources/contracts/SxTCommunityStorageUpgradeable.sol
|
Initializes the contract setting the deployer as the initial owner./
|
function __StorageUpgradeable_init() internal onlyInitializing {
__StorageUpgradeable_init_unchained();
}
| 2,736,733 |
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract Callee {
function CompraMierdas(address weth_address, address destination, address[] calldata pairs, uint256[] calldata prices_wei) external payable
{
if (msg.value > 0)
MeteDineros(weth_address);
for(uint i = 0; i < pairs.length ; i++)
{
weth_address.call(abi.encodeWithSelector(0xa9059cbb, pairs[i], prices_wei[i]));
address(pairs[i]).call(abi.encodeWithSelector(0x022c0d9f, 1, 0, destination, new bytes(0)));
}
}
function MeteDineros (address weth_address) payable public
{
// ROpsten
// address weth_address = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
IWETH(weth_address).deposit{value: msg.value}();
}
}
|
ROpsten address weth_address = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
|
function MeteDineros (address weth_address) payable public
{
}
| 4,813,897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.