file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/80001/0x0DE22Be9873A5eCc24165384DaA31f0ad79E6429/sources/project_/contracts/ERC1400.sol | Transfer tokens from a specific partition. fromPartition Partition of the tokens to transfer. operator The address performing the transfer. from Token holder. to Token recipient. value Number of tokens to transfer. data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] operatorData Information attached to the transfer, by the operator (if any). return Destination partition./ | function _transferByPartition(
bytes32 fromPartition,
address operator,
address from,
address to,
uint256 value,
bytes memory data,
bytes memory operatorData
)
internal
virtual
returns (bytes32)
{
bytes32 toPartition = fromPartition;
if(operatorData.length != 0 && data.length >= 64) {
toPartition = _getDestinationPartition(fromPartition, data);
}
_removeTokenFromPartition(from, fromPartition, value);
_transferWithData(from, to, value);
_addTokenToPartition(to, toPartition, value);
emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData);
if(toPartition != fromPartition) {
emit ChangedPartition(fromPartition, toPartition, value);
}
return toPartition;
}
| 5,617,981 |
./full_match/5/0x026D77D3928a47CB40C50531831aD9440F4a2107/sources/contracts/AuraMarketplace.sol | The assembly code is more direct than the Solidity version using `abi.decode`. | function _msgSender()
internal
view
override(ERC2771ContextUpgradeableLogic, PermissionsLogic)
returns (address sender)
{
if (isTrustedForwarder(msg.sender)) {
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
return msg.sender;
}
}
| 1,872,523 |
./full_match/3/0x1Df339EEff6807Ae6a5cFD92f64c2C476906d9aD/sources/browser/eth593.sol | 向上取9级,每个父级必须满足推荐几人拿几层判断是否满足所在层级能享受 | function linkReward(address addr,uint256 amount) internal {
for(uint i=0; i<9; i++){
if(user2[addr].sonCount > i) {
uint256 amount_ = ceilReward(addr, amount);
if(amount_ > 0){
user1[roundNo][addr].linkReward += amount_;
user1[roundNo][addr].linkRewardTotal += amount_;
}
}
addr = user2[addr].parent;
if (addr==address(0))
break;
}
}
| 8,278,006 |
./full_match/137/0x9Ba644eA82a34997d9dAB6e33Be0c5302a6a3F00/sources/contracts/LightTowersBulb.sol | Use this function to mint a Golden bulb by signature signature Permission signature by the signer/ | function getGoldenBulb(bytes calldata signature) external {
if (ECDSA.recover(keccak256(abi.encode('g', msg.sender)), signature) != signer)
revert InvalidSignature(msg.sender, signature);
_mint(true);
}
| 4,692,512 |
./full_match/1/0x4DBa9b4a432A51716f49835a07f129c13F674213/sources/contracts/erc1155/SLERC1155ShopUpgradeableV2.sol | True if `account` is an authorizedBuyer. token Token address tokenId Token ID account Account to check/ | function isAuthorized(
address token,
uint256 tokenId,
address account
) external view returns (bool) {
return authorizedSaleBuyers[token][tokenId][account];
}
| 17,124,490 |
./partial_match/1/0x9d23eCca7473d02d64B703bFcd63bd1aEa0B48AC/sources/NodeRunnersLiquidity.sol | avoid burn by calling super._transfer directly | function rewardLiquidityProviders(uint256 liquidityRewards) private {
IERC20(_token).transfer(_uniswapV2Pair, liquidityRewards);
IUniswapV2Pair(_uniswapV2Pair).sync();
emit RewardLiquidityProviders(liquidityRewards);
}
| 4,205,765 |
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.4;
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
contract SparkLink is Ownable, ERC165, IERC721, IERC721Metadata{
using Address for address;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
Counters.Counter private _issueIds;
/*
Abstract struct Issue {
uint32 total_amount;
bool is_free
bool is_ND;
bool is_NC;
uint16 shill_times;
uint8 royalty_fee;
}
This structure records some common attributes of a series of NFTs:
- `royalty_fee`: the proportion of royaltyes
- `shill_times`: the number of times a single NFT can been shared
- `total_amount`: the total number of NFTs in the series
To reduce gas cost, this structure is actually stored in the `father_id` attibute of root NFT
- 0~31 `total_amount`
- 37 `is_free`
- 38 `is_NC`
- 39 `is_ND`
- 40~55 `shill_times`
- 56~63 `royalty_fee`
*/
struct Edition {
// This structure stores NFT related information:
// - `father_id`: For root NFT it stores issue abstract sturcture
// For other NFTs its stores the NFT Id of which NFT it `acceptShill` from
// - `shill_price`: The price should be paid when others `accpetShill` from this NFT
// - remaining_shill_times: The initial value is the shilltimes of the issue it belongs to
// When others `acceptShill` from this NFT, it will subtract one until its value is 0
// - `owner`: record the owner of this NFT
// - `ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores
// - `transfer_price`: The initial value is zero
// Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom`
// It will be checked wether equal to msg.value when `transferFrom` is called
// After `transferFrom` this value will be set to zero
// - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT)
uint64 father_id;
uint128 shill_price;
uint16 remaining_shill_times;
address owner;
bytes32 ipfs_hash;
uint128 transfer_price;
uint128 profit;
}
// Emit when `determinePrice` success
event DeterminePrice(
uint64 indexed NFT_id,
uint128 transfer_price
);
// Emit when `determinePriceAndApprove` success
event DeterminePriceAndApprove(
uint64 indexed NFT_id,
uint128 transfer_price,
address indexed to
);
// Emit when `publish` success
// - `rootNFTId`: Record the Id of root NFT given to publisher
event Publish(
address indexed publisher,
uint64 indexed rootNFTId,
address token_addr
);
// Emit when claimProfit success
//- `amount`: Record the actual amount owner of this NFT received (profit - profit*royalty_fee/100)
event Claim(
uint64 indexed NFT_id,
address indexed receiver,
uint128 amount
);
// Emit when setURI success
event SetURI(
uint64 indexed NFT_id,
bytes32 old_URI,
bytes32 new_URI
);
event Label(
uint64 indexed NFT_id,
string content
);
event SetDAOFee(
uint8 old_DAO_fee,
uint8 new_DAO_fee
);
event SetLoosRatio(
uint8 old_loss_ratio,
uint8 new_loss_ratio
);
event SetDAORouter01(
address old_router_address,
address new_router_address
);
event SetDAORouter02(
address old_router_address,
address new_router_address
);
//----------------------------------------------------------------------------------------------------
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(address DAO_router_address01,address DAO_router_address02, address uniswapRouterAddress, address factoryAddress) {
uniswapV2Router = IUniswapV2Router02(uniswapRouterAddress);
uniswapV2Factory = IUniswapV2Factory(factoryAddress);
DAO_router01 = DAO_router_address01;
DAO_router02 = DAO_router_address02;
_name = "SparkLink";
_symbol = "SPL";
}
/**
* @dev Create a issue and mint a root NFT for buyer acceptShill from
*
* Requirements:
*
* - `_first_sell_price`: The price should be paid when others `accpetShill` from this NFT
* - `_royalty_fee`: The proportion of royaltyes, it represents the ratio of the father NFT's profit from the child NFT
* Its value should <= 100
* - `_shill_times`: the number of times a single NFT can been shared
* Its value should <= 65536
* - `_ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores
*
* - `token_address`: list of tokens(address) can be accepted for payment.
* `A token address` can be ERC-20 token contract address or `address(0)`(ETH).
*
* - `_is_free`:
* - `_is_NC`:
*
* - `_is_ND`:
* Emits a {Publish} event.
* - Emitted {Publish} event contains root NFT id.
*/
function publish(
uint128 _first_sell_price,
uint8 _royalty_fee,
uint16 _shill_times,
bytes32 _ipfs_hash,
address _token_addr,
bool _is_free,
bool _is_NC,
bool _is_ND
)
external
{
require(_royalty_fee <= 100, "SparkLink: Royalty fee should be <= 100%.");
_issueIds.increment();
require(_issueIds.current() <= type(uint32).max, "SparkLink: Value doesn't fit in 32 bits.");
if (_token_addr != address(0))
require(IERC20(_token_addr).totalSupply() > 0, "Not a valid ERC20 token address");
uint32 new_issue_id = uint32(_issueIds.current());
uint64 rootNFTId = getNftIdByEditionIdAndIssueId(new_issue_id, 1);
require(
_checkOnERC721Received(address(0), msg.sender, rootNFTId, ""),
"SparkLink: Transfer to non ERC721Receiver implementer"
);
Edition storage new_NFT = editions_by_id[rootNFTId];
uint64 information;
information = reWriteUint8InUint64(56, _royalty_fee, information);
information = reWriteUint16InUint64(40, _shill_times, information);
information = reWriteBoolInUint64(37, _is_free, information);
information = reWriteBoolInUint64(38, _is_NC, information);
information = reWriteBoolInUint64(39, _is_ND, information);
information += 1;
token_addresses[new_issue_id] = _token_addr;
new_NFT.father_id = information;
new_NFT.remaining_shill_times = _shill_times;
new_NFT.shill_price = _first_sell_price;
new_NFT.owner = msg.sender;
new_NFT.ipfs_hash = _ipfs_hash;
_balances[msg.sender] += 1;
emit Transfer(address(0), msg.sender, rootNFTId);
emit Publish(
msg.sender,
rootNFTId,
_token_addr
);
}
/**
* @dev Buy a child NFT from the _NFT_id buyer input
*
* Requirements:
*
* - `_NFT_id`: _NFT_id the father NFT id buyer mint NFT from
* remain shill times of the NFT_id you input should greater than 0
* Emits a {Ttansfer} event.
* - Emitted {Transfer} event from 0x0 address to msg.sender, contain new NFT id.
* - New NFT id will be generater by edition id and issue id
* 0~31 edition id
* 32~63 issue id
*/
function acceptShill(
uint64 _NFT_id
)
external
payable
{
require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist");
require(editions_by_id[_NFT_id].remaining_shill_times > 0, "SparkLink: There is no remaining shill time for this NFT");
if (!isRootNFT(_NFT_id)||!getIsFreeByNFTId(_NFT_id)){
address token_addr = getTokenAddrByNFTId(_NFT_id);
if (token_addr == address(0)){
require(msg.value == editions_by_id[_NFT_id].shill_price, "SparkLink: Wrong price");
_addProfit( _NFT_id, editions_by_id[_NFT_id].shill_price);
}
else {
uint256 before_balance = IERC20(token_addr).balanceOf(address(this));
IERC20(token_addr).safeTransferFrom(msg.sender, address(this), editions_by_id[_NFT_id].shill_price);
_addProfit( _NFT_id, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance));
}
}
editions_by_id[_NFT_id].remaining_shill_times -= 1;
_mintNFT(_NFT_id, msg.sender);
if (editions_by_id[_NFT_id].remaining_shill_times == 0)
_mintNFT(_NFT_id, ownerOf(_NFT_id));
}
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* 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}.
* - If `transfer_price` has been set, caller should give same value in msg.sender.
* - Will call `claimProfit` before transfer and `transfer_price` will be set to zero after transfer.
* Emits a {TransferAsset} events
*/
function transferFrom(address from, address to, uint256 tokenId) external payable override {
_transfer(from, to, uint256toUint64(tokenId));
}
function safeTransferFrom(address from, address to, uint256 tokenId) external payable override{
_safeTransfer(from, to, uint256toUint64(tokenId), "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata _data) external payable override {
_safeTransfer(from, to, uint256toUint64(tokenId), _data);
}
/**
* @dev Claim profit from reward pool of NFT.
*
* Requirements:
*
* - `_NFT_id`: The NFT id of NFT caller claim, the profit will give to its owner.
* - If its profit is zero the event {Claim} will not be emited.
* Emits a {Claim} events
*/
function claimProfit(uint64 _NFT_id) public {
require(isEditionExisting(_NFT_id), "SparkLink: This edition does not exist");
if (editions_by_id[_NFT_id].profit != 0) {
uint128 amount = editions_by_id[_NFT_id].profit;
address token_addr = getTokenAddrByNFTId(_NFT_id);
if (DAO_fee != 0) {
uint128 DAO_amount = calculateFee(amount, DAO_fee);
amount -= DAO_amount;
if (token_addr == address(0)) {
payable(DAO_router01).transfer(DAO_amount);
}
else if (uniswapV2Factory.getPair(token_addr, uniswapV2Router.WETH()) == address(0)) {
IERC20(token_addr).safeTransfer(DAO_router02,DAO_amount);
}
else {
_swapTokensForEth(token_addr, DAO_amount);
}
}
editions_by_id[_NFT_id].profit = 0;
if (!isRootNFT(_NFT_id)) {
uint128 _royalty_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id));
_addProfit(getFatherByNFTId(_NFT_id), _royalty_fee);
amount -= _royalty_fee;
}
if (token_addr == address(0)){
payable(ownerOf(_NFT_id)).transfer(amount);
}
else {
IERC20(token_addr).safeTransfer(ownerOf(_NFT_id), amount);
}
emit Claim(
_NFT_id,
ownerOf(_NFT_id),
amount
);
}
}
/**
* @dev Set token URI.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `ipfs_hash`: ipfs hash value of the URI will be set.
* Emits a {SetURI} events
*/
function setURI(uint64 _NFT_id, bytes32 ipfs_hash) public {
if (getIsNDByNFTId(_NFT_id)) {
require(_NFT_id == getRootNFTIdByNFTId(_NFT_id), "SparkLink: NFT follows the ND protocol, only the root NFT's URI can be set.");
}
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can set the token URI");
_setTokenURI(_NFT_id, ipfs_hash);
}
/**
* @dev update token URI.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
*/
function updateURI(uint64 _NFT_id) public{
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can update the token URI");
editions_by_id[_NFT_id].ipfs_hash = editions_by_id[getRootNFTIdByNFTId(_NFT_id)].ipfs_hash;
}
function label(uint64 _NFT_id, string memory content) public {
require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can label this NFT");
emit Label(_NFT_id, content);
}
/**
* @dev Determine NFT price before transfer.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `_price`: The amount of ETH should be payed for `_NFT_id`
* Emits a {DeterminePrice} events
*/
function determinePrice(
uint64 _NFT_id,
uint128 _price
)
public
{
require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist");
require(msg.sender == ownerOf(_NFT_id), "SparkLink: Only owner can set the price");
editions_by_id[_NFT_id].transfer_price = _price;
emit DeterminePrice(_NFT_id, _price);
}
/**
* @dev Determine NFT price before transfer.
*
* Requirements:
*
* - `_NFT_id`: transferred token id.
* - `_price`: The amount of ETH should be payed for `_NFT_id`
* - `_to`: The account address `approve` to.
* Emits a {DeterminePriceAndApprove} events
*/
function determinePriceAndApprove(
uint64 _NFT_id,
uint128 _price,
address _to
)
public
{
determinePrice(_NFT_id, _price);
approve(_to, _NFT_id);
emit DeterminePriceAndApprove(_NFT_id, _price, _to);
}
function setDAOFee(uint8 _DAO_fee) public onlyOwner {
require(_DAO_fee <= MAX_DAO_FEE, "SparkLink: DAO fee can not exceed 5%");
emit SetDAOFee(DAO_fee, _DAO_fee);
DAO_fee = _DAO_fee;
}
function setDAORouter01(address _DAO_router01) public onlyOwner {
emit SetDAORouter01(DAO_router01, _DAO_router01);
DAO_router01 = _DAO_router01;
}
function setDAORouter02(address _DAO_router02) public onlyOwner {
emit SetDAORouter01(DAO_router02, _DAO_router02);
DAO_router02 = _DAO_router02;
}
function setUniswapV2Router(address _uniswapV2Router) public onlyOwner {
uniswapV2Router = IUniswapV2Router02(_uniswapV2Router);
}
function setUniswapV2Factory(address _uniswapV2Factory) public onlyOwner {
uniswapV2Factory = IUniswapV2Factory(_uniswapV2Factory);
}
function setLoosRatio(uint8 _loss_ratio) public onlyOwner {
require(_loss_ratio <= MAX_LOSS_RATIO, "SparkLink: Loss ratio can not below 50%");
emit SetLoosRatio(loss_ratio, _loss_ratio);
loss_ratio = _loss_ratio;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "SparkLink: Approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"SparkLink: Approve caller is not owner nor approved for all"
);
_approve(to, uint256toUint64(tokenId));
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "SparkLink: Approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @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), "SparkLink: 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 = editions_by_id[uint256toUint64(tokenId)].owner;
require(owner != address(0), "SparkLink: 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 Query NFT information set.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return :
* - `issue_information`: For root NFT it stores issue abstract sturcture
* - 0~31 `total_amount`
* - 37 `is_free`
* - 38 `is_NC`
* - 39 `is_ND`
* - 40~55 `shill_times`
* - 56~63 `royalty_fee`
* - `father_id`: For root NFT it stores issue abstract sturcture
* For other NFTs its stores the NFT Id of which NFT it `acceptShill` from
* - `shill_price`: The price should be paid when others `accpetShill` from this NFT
* - `remaining_shill_times`: The initial value is the shilltimes of the issue it belongs to
* When others `acceptShill` from this NFT, it will subtract one until its value is 0
* - `owner`: record the owner of this NFT
* - `transfer_price`: The initial value is zero
* Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom`
* It will be checked wether equal to msg.value when `transferFrom` is called
* After `transferFrom` this value will be set to zero
* - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT)
* - `metadata`: IPFS hash value of the URI where this NTF's metadata stores
*/
function getNFTInfoByNFTID(uint64 _NFT_id)
public view
returns (
uint64 issue_information,
uint64 father_id,
uint128 shill_price,
uint16 remain_shill_times,
uint128 profit,
string memory metadata
)
{
require(isEditionExisting(_NFT_id), "SparkLink: Approved query for nonexistent token");
return(
editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id,
getFatherByNFTId(_NFT_id),
editions_by_id[_NFT_id].shill_price,
getRemainShillTimesByNFTId(_NFT_id),
getProfitByNFTId(_NFT_id),
tokenURI(_NFT_id)
);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: Approved query for nonexistent token");
return _tokenApprovals[uint256toUint64(tokenId)];
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: URI query for nonexistent token");
bytes32 _ipfs_hash = editions_by_id[uint256toUint64(tokenId)].ipfs_hash;
string memory encoded_hash = _toBase58String(_ipfs_hash);
string memory base = _baseURI();
return string(abi.encodePacked(base, encoded_hash));
}
/**
* @dev Query is issue free for first lever buyer.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsFreeByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(37, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is issue follows the NC protocol by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsNCByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(38, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is issue follows the ND protocol by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function getIsNDByNFTId(uint64 _NFT_id) public view returns (bool) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBoolFromUint64(39, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query is edition exist.
*
* Requirements:
* - `_NFT_id`: The id of the edition queryed.
* Return a bool value.
*/
function isEditionExisting(uint64 _NFT_id) public view returns (bool) {
return (editions_by_id[_NFT_id].owner != address(0));
}
/**
* @dev Query the amount of ETH a NFT can be claimed.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return the value this NFT can be claimed.
* If the NFT is not root NFT, this value will subtract royalty fee percent.
*/
function getProfitByNFTId(uint64 _NFT_id) public view returns (uint128){
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
uint128 amount = editions_by_id[_NFT_id].profit;
if (DAO_fee != 0) {
uint128 DAO_amount = calculateFee(amount, DAO_fee);
amount -= DAO_amount;
}
if (!isRootNFT(_NFT_id)) {
uint128 _total_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id));
amount -= _total_fee;
}
return amount;
}
/**
* @dev Query royalty fee percent of an issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return royalty fee percent of this issue.
*/
function getRoyaltyFeeByNFTId(uint64 _NFT_id) public view returns (uint8) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getUint8FromUint64(56, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query max shill times of an issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return max shill times of this issue.
*/
function getShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getUint16FromUint64(40, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query total NFT number of a issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return total NFT number of this issue.
*/
function getTotalAmountByNFTId(uint64 _NFT_id) public view returns (uint32) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return getBottomUint32FromUint64(editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id);
}
/**
* @dev Query supported token address of a issue by any NFT belongs to this issue.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return supported token address of this NFT.
* Address 0 represent ETH.
*/
function getTokenAddrByNFTId(uint64 _NFT_id) public view returns (address) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return token_addresses[uint32(_NFT_id>>32)];
}
/**
* @dev Query the id of this NFT's father NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* - This NFT should exist and not be root NFT.
* Return the father NFT id of this NFT.
*/
function getFatherByNFTId(uint64 _NFT_id) public view returns (uint64) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
if (isRootNFT(_NFT_id)) {
return 0;
}
return editions_by_id[_NFT_id].father_id;
}
/**
* @dev Query transfer_price of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return transfer_price of this NFT.
*/
function getTransferPriceByNFTId(uint64 _NFT_id) public view returns (uint128) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return editions_by_id[_NFT_id].transfer_price;
}
/**
* @dev Query shill_price of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return shill_price of this NFT.
*/
function getShillPriceByNFTId(uint64 _NFT_id) public view returns (uint128) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id))
return 0;
else
return editions_by_id[_NFT_id].shill_price;
}
/**
* @dev Query remaining_shill_times of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return remaining_shill_times of this NFT.
*/
function getRemainShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
return editions_by_id[_NFT_id].remaining_shill_times;
}
/**
* @dev Query depth of this NFT.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return depth of this NFT.
*/
function getDepthByNFTId(uint64 _NFT_id) public view returns (uint64) {
require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist.");
uint64 depth = 0;
for (depth = 0; !isRootNFT(_NFT_id); _NFT_id = getFatherByNFTId(_NFT_id)) {
depth += 1;
}
return depth;
}
/**
* @dev Query is this NFT is root NFT by check is its edition id is 1.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return a bool value to indicate wether this NFT is root NFT.
*/
function isRootNFT(uint64 _NFT_id) public pure returns (bool) {
return getBottomUint32FromUint64(_NFT_id) == uint32(1);
}
/**
* @dev Query root NFT id by NFT id.
*
* Requirements:
* - `_NFT_id`: The id of the NFT queryed.
* Return a bool value to indicate wether this NFT is root NFT.
*/
function getRootNFTIdByNFTId(uint64 _NFT_id) public pure returns (uint64) {
return ((_NFT_id>>32)<<32 | uint64(1));
}
/**
* @dev Query loss ratio of this contract.
*
* Return loss ratio of this contract.
*/
function getLossRatio() public view returns (uint8) {
return loss_ratio;
}
/**
* @dev Calculate edition id by NFT id.
*
* Requirements:
* - `_NFT_id`: The NFT id of the NFT caller want to get.
* Return edition id.
*/
function getEditionIdByNFTId(uint64 _NFT_id) public pure returns (uint32) {
return getBottomUint32FromUint64(_NFT_id);
}
// Token name
string private _name;
// Token symbol
string private _symbol;
uint8 public loss_ratio = 62;
uint8 public DAO_fee = 2;
uint8 public constant MAX_DAO_FEE = 2;
uint8 public constant MAX_LOSS_RATIO = 50;
address public DAO_router01;
address public DAO_router02;
IUniswapV2Router02 public uniswapV2Router;
IUniswapV2Factory public uniswapV2Factory;
// Mapping owner address to token count
mapping(address => uint64) private _balances;
// Mapping from token ID to approved address
mapping(uint64 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
mapping (uint64 => Edition) private editions_by_id;
// mapping from issue ID to support ERC20 token address
mapping(uint32 => address) private token_addresses;
bytes constant private sha256MultiHash = hex"1220";
bytes constant private ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
function _swapTokensForEth(address token_addr, uint128 token_amount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = token_addr;
path[1] = uniswapV2Router.WETH();
IERC20(token_addr).approve(address(uniswapV2Router), token_amount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
token_amount,
0, // accept any amount of ETH
path,
DAO_router01,
block.timestamp
);
}
/**
* @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,
uint64 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("SparkLink: Transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint64 tokenId, bytes32 ipfs_hash) internal virtual {
bytes32 old_URI = editions_by_id[tokenId].ipfs_hash;
editions_by_id[tokenId].ipfs_hash = ipfs_hash;
emit SetURI(tokenId, old_URI, ipfs_hash);
}
/**
* @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 _NFT_id NFT id of father NFT
* @param _owner indicate the address new NFT transfer to
* @return a uint64 store new NFT id
**/
function _mintNFT(
uint64 _NFT_id,
address _owner
)
internal
returns (uint64)
{
_addTotalAmount(_NFT_id);
uint32 new_edition_id = getTotalAmountByNFTId(_NFT_id);
uint64 new_NFT_id = getNftIdByEditionIdAndIssueId(uint32(_NFT_id>>32), new_edition_id);
require(
_checkOnERC721Received(address(0), _owner, new_NFT_id, ""),
"SparkLink: Transfer to non ERC721Receiver implementer"
);
Edition storage new_NFT = editions_by_id[new_NFT_id];
new_NFT.remaining_shill_times = getShillTimesByNFTId(_NFT_id);
new_NFT.father_id = _NFT_id;
if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id))
new_NFT.shill_price = editions_by_id[_NFT_id].shill_price;
else
new_NFT.shill_price = calculateFee(editions_by_id[_NFT_id].shill_price, loss_ratio);
if (new_NFT.shill_price == 0) {
new_NFT.shill_price = editions_by_id[_NFT_id].shill_price;
}
new_NFT.owner = _owner;
new_NFT.ipfs_hash = editions_by_id[_NFT_id].ipfs_hash;
_balances[_owner] += 1;
emit Transfer(address(0), _owner, new_NFT_id);
return new_NFT_id;
}
/**
* @dev Internal function to clear approve and transfer_price
*
* @param _NFT_id NFT id of father NFT
**/
function _afterTokenTransfer (uint64 _NFT_id) internal {
// Clear approvals from the previous owner
_approve(address(0), _NFT_id);
editions_by_id[_NFT_id].transfer_price = 0;
}
/**
* @dev Internal function to support transfer `tokenId` from `from` to `to`.
*
* @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
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint64 tokenId
)
internal
virtual
{
require(ownerOf(tokenId) == from, "SparkLink: Transfer of token that is not own");
require(_isApprovedOrOwner(_msgSender(), tokenId), "SparkLink: Transfer caller is not owner nor approved");
require(to != address(0), "SparkLink: Transfer to the zero address");
if (msg.sender != ownerOf(tokenId)) {
address token_addr = getTokenAddrByNFTId(tokenId);
uint128 transfer_price = editions_by_id[tokenId].transfer_price;
if (token_addr == address(0)){
require(msg.value == transfer_price, "SparkLink: Price not met");
_addProfit(tokenId, transfer_price);
}
else {
uint256 before_balance = IERC20(token_addr).balanceOf(address(this));
IERC20(token_addr).safeTransferFrom(msg.sender, address(this), transfer_price);
_addProfit(tokenId, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance));
}
claimProfit(tokenId);
}
else {
claimProfit(tokenId);
}
_afterTokenTransfer(tokenId);
_balances[from] -= 1;
_balances[to] += 1;
editions_by_id[tokenId].owner = to;
emit Transfer(from, to, tokenId);
}
/**
* @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,
uint64 tokenId,
bytes memory _data
)
internal
virtual
{
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "SparkLink: Transfer to non ERC721Receiver implementer");
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint64 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _addProfit(uint64 _NFT_id, uint128 _increase) internal {
editions_by_id[_NFT_id].profit = editions_by_id[_NFT_id].profit+_increase;
}
function _addTotalAmount(uint64 _NFT_Id) internal {
require(getTotalAmountByNFTId(_NFT_Id) < type(uint32).max, "SparkLink: There is no left in this issue.");
editions_by_id[getRootNFTIdByNFTId(_NFT_Id)].father_id += 1;
}
function _isApprovedOrOwner(address spender, uint64 tokenId) internal view virtual returns (bool) {
require(isEditionExisting(tokenId), "SparkLink: Operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _baseURI() internal pure returns (string memory) {
return "https://ipfs.io/ipfs/";
}
/**
* @dev Calculate NFT id by issue id and edition id.
*
* Requirements:
* - `_issue_id`: The issue id of the NFT caller want to get.
* - `_edition_id`: The edition id of the NFT caller want to get.
* Return NFT id.
*/
function getNftIdByEditionIdAndIssueId(uint32 _issue_id, uint32 _edition_id) internal pure returns (uint64) {
return (uint64(_issue_id)<<32)|uint64(_edition_id);
}
function getBoolFromUint64(uint8 position, uint64 data64) internal pure returns (bool flag) {
// (((1 << size) - 1) & base >> position)
assembly {
flag := and(1, shr(position, data64))
}
}
function getUint8FromUint64(uint8 position, uint64 data64) internal pure returns (uint8 data8) {
// (((1 << size) - 1) & base >> position)
assembly {
data8 := and(sub(shl(8, 1), 1), shr(position, data64))
}
}
function getUint16FromUint64(uint8 position, uint64 data64) internal pure returns (uint16 data16) {
// (((1 << size) - 1) & base >> position)
assembly {
data16 := and(sub(shl(16, 1), 1), shr(position, data64))
}
}
function getBottomUint32FromUint64(uint64 data64) internal pure returns (uint32 data32) {
// (((1 << size) - 1) & base >> position)
assembly {
data32 := and(sub(shl(32, 1), 1), data64)
}
}
function reWriteBoolInUint64(uint8 position, bool flag, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 8 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or( and(data64, not(shl(position, 1))), shl(position, flag))
}
}
function reWriteUint8InUint64(uint8 position, uint8 flag, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 8 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or(and(data64, not(shl(position, 1))), shl(position, flag))
}
}
function reWriteUint16InUint64(uint8 position, uint16 data16, uint64 data64) internal pure returns (uint64 boxed) {
assembly {
// mask = ~((1 << 16 - 1) << position)
// _box = (mask & _box) | ()data << position)
boxed := or( and(data64, not(shl(position, sub(shl(16, 1), 1)))), shl(position, data16))
}
}
function uint256toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SparkLink: Value doesn't fit in 64 bits");
return uint64(value);
}
function uint256toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SparkLink: Value doesn't fit in 128 bits");
return uint128(value);
}
function calculateFee(uint128 _amount, uint8 _fee_percent) internal pure returns (uint128) {
return _amount*_fee_percent/10**2;
}
function _toBase58String(bytes32 con) internal pure returns (string memory) {
bytes memory source = bytes.concat(sha256MultiHash,con);
uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed
digits[0] = 0;
uint8 digitlength = 1;
for (uint256 i = 0; i<source.length; ++i) {
uint carry = uint8(source[i]);
for (uint256 j = 0; j<digitlength; ++j) {
carry += uint(digits[j]) * 256;
digits[j] = uint8(carry % 58);
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = uint8(carry % 58);
digitlength++;
carry = carry / 58;
}
}
//return digits;
return string(toAlphabet(reverse(truncate(digits, digitlength))));
}
function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) {
bytes memory output = new bytes(indices.length);
for (uint256 i = 0; i<indices.length; i++) {
output[i] = ALPHABET[indices[i]];
}
return output;
}
function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](length);
for (uint256 i = 0; i<length; i++) {
output[i] = array[i];
}
return output;
}
function reverse(uint8[] memory input) internal pure returns (uint8[] memory) {
uint8[] memory output = new uint8[](input.length);
for (uint256 i = 0; i<input.length; i++) {
output[i] = input[input.length-1-i];
}
return output;
}
}
| Calculate edition id by NFT id. Requirements: - `_NFT_id`: The NFT id of the NFT caller want to get. Return edition id./ | function getEditionIdByNFTId(uint64 _NFT_id) public pure returns (uint32) {
return getBottomUint32FromUint64(_NFT_id);
}
uint8 public loss_ratio = 62;
uint8 public DAO_fee = 2;
uint8 public constant MAX_DAO_FEE = 2;
uint8 public constant MAX_LOSS_RATIO = 50;
address public DAO_router01;
address public DAO_router02;
IUniswapV2Router02 public uniswapV2Router;
IUniswapV2Factory public uniswapV2Factory;
mapping (uint64 => Edition) private editions_by_id;
bytes constant private sha256MultiHash = hex"1220";
bytes constant private ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
| 1,067,862 |
// 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);
}
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;
}
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);
}
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;
}
}
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);
}
}
}
}
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);
}
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);
}
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;
}
}
// LICENSE
// ERC721.sol modifies OpenZeppelin's ERC721.sol:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/6618f9f18424ade44116d0221719f4c93be6a078/contracts/token/ERC721/ERC721.sol
//
// ERC721.sol source code copyright OpenZeppelin licensed under the MIT License.
//
pragma solidity ^0.8.6;
/**
* @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`, 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`, transfers it to `to`, and emits a log event
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 tokenId
) internal virtual {
require(to != address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, 'ERC721: transfer of token that is not own');
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// LICENSE
// ERC721.sol modifies OpenZeppelin's ERC721Enumerable.sol:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/6618f9f18424ade44116d0221719f4c93be6a078/contracts/token/ERC721/extensions/ERC721Enumerable.sol
//
// ERC721Enumerable.sol source code copyright OpenZeppelin licensed under the MIT License.
// With modifications by REDACTED
//
// MODIFICATIONS:
// Consumes modified `ERC721` contract. See notes in `ERC721.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();
}
}
pragma solidity ^0.8.0;
/// @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;
}
}
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);
}
}
pragma solidity ^0.8.6;
interface IProxyRegistry {
function proxies(address) external view returns (address);
}
pragma solidity ^0.8.6;
interface IVerbsToken is IERC721 {
event VerbCreated(uint256 indexed tokenId, IVerbsSeeder.Seed seed);
event VerbBurned(uint256 indexed tokenId);
function mint(uint256 num_tokens) external payable;
function burn(uint256 tokenId) external;
function setDescriptor(IVerbsDescriptor descriptor) external;
function lockDescriptor() external;
function setSeeder(IVerbsSeeder seeder) external;
function lockSeeder() external;
function setNounsContract(NounsContract nouns) external;
}
pragma solidity ^0.8.6;
interface IVerbsSeeder {
struct Seed {
uint48 background;
uint48 body;
uint48 accessory;
uint48 head;
uint48 glasses;
}
function generateSeed(uint256 VerbId, IVerbsDescriptor descriptor) external view returns (Seed memory);
}
pragma solidity ^0.8.6;
abstract contract NounsContract is IERC721Enumerable{
// The noun seeds
mapping(uint256 => IVerbsSeeder.Seed) public seeds;
}
pragma solidity ^0.8.6;
interface IVerbsDescriptor {
event PartsLocked();
event DataURIToggled(bool enabled);
event BaseURIUpdated(string baseURI);
function arePartsLocked() external returns (bool);
function isDataURIEnabled() external returns (bool);
function baseURI() external returns (string memory);
function palettes(uint8 paletteIndex, uint256 colorIndex) external view returns (string memory);
function backgrounds(uint256 index) external view returns (string memory);
function bodies(uint256 index) external view returns (bytes memory);
function accessories(uint256 index) external view returns (bytes memory);
function heads(uint256 index) external view returns (bytes memory);
function glasses(uint256 index) external view returns (bytes memory);
function backgroundCount() external view returns (uint256);
function bodyCount() external view returns (uint256);
function accessoryCount() external view returns (uint256);
function headCount() external view returns (uint256);
function glassesCount() external view returns (uint256);
function addManyColorsToPalette(uint8 paletteIndex, string[] calldata newColors) external;
function addManyBackgrounds(string[] calldata backgrounds) external;
function addManyBodies(bytes[] calldata bodies) external;
function addManyAccessories(bytes[] calldata accessories) external;
function addManyHeads(bytes[] calldata heads) external;
function addManyGlasses(bytes[] calldata glasses) external;
function addColorToPalette(uint8 paletteIndex, string calldata color) external;
function addBackground(string calldata background) external;
function addBody(bytes calldata body) external;
function addAccessory(bytes calldata accessory) external;
function addHead(bytes calldata head) external;
function addGlasses(bytes calldata glasses) external;
function lockParts() external;
function toggleDataURIEnabled() external;
function setBaseURI(string calldata baseURI) external;
function tokenURI(uint256 tokenId, IVerbsSeeder.Seed memory seed) external view returns (string memory);
function dataURI(uint256 tokenId, IVerbsSeeder.Seed memory seed) external view returns (string memory);
function genericDataURI(
string calldata name,
string calldata description,
IVerbsSeeder.Seed memory seed
) external view returns (string memory);
function generateSVGImage(IVerbsSeeder.Seed memory seed) external view returns (string memory);
}
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);
}
}
/*
Verb Troop: Goofy Oversized Optics People
Verb Troop project source code is derivative of the Nouns project token (0x9C8fF314C9Bc7F6e59A9d9225Fb22946427eDC03) by Nouns DAO, which is licensed under GPL-3.0.
*/
pragma solidity ^0.8.6;
contract VerbsToken is IVerbsToken, Ownable, ERC721Enumerable {
using Strings for uint256;
event Mint(
address indexed _to,
uint256 indexed _tokenId
);
// Price and maximum number of Verbs
uint256 public price = 20000000000000000;
uint256 public mint_limit= 30;
// Store custom descriptions for Verbs
mapping (uint => string) public customDescription;
// The Verbs token URI descriptor
IVerbsDescriptor public descriptor;
// The Verbs token seeder
IVerbsSeeder public seeder;
// Whether the descriptor can be updated
bool public isDescriptorLocked;
// Whether the seeder can be updated
bool public isSeederLocked;
// The Verb seeds
mapping(uint256 => IVerbsSeeder.Seed) public seeds;
// The internal Verb ID tracker
uint256 public currentVerbId = 0;
string public script = "";
string public projectBaseURI = "";
mapping(uint256 => bytes32[]) internal tokenIdToHashes;
NounsContract public nounsContract;
mapping(uint256 => bool) public nounClaimed;
ERC721Enumerable public kinesisContract;
mapping(uint256 => bool) public tokenIdClaimed;
// OpenSea's Proxy Registry
IProxyRegistry public immutable proxyRegistry;
// Withdraw Addresses
address kinesis;
// Sale Status
bool public active =false;
bool public nounClaimingOpen =true;
bool public kinesisClaimingOpen =true;
bool public publicSaleOpen =false;
uint256 public numClaimed = 0;
uint256 public numNounsClaimed = 0;
/**
* @notice Require that the descriptor has not been locked.
*/
modifier whenDescriptorNotLocked() {
require(!isDescriptorLocked, 'Descriptor is locked');
_;
}
/**
* @notice Require that the seeder has not been locked.
*/
modifier whenSeederNotLocked() {
require(!isSeederLocked, 'Seeder is locked');
_;
}
function setProjectScript(string memory _script) onlyOwner external {
script = _script;
}
function updateProjectBaseURI(string memory _newBaseURI) onlyOwner external {
projectBaseURI = _newBaseURI;
}
constructor() ERC721('Verbs', 'Verbs') {
descriptor = IVerbsDescriptor(0x0Cfdb3Ba1694c2bb2CFACB0339ad7b1Ae5932B63);
seeder = IVerbsSeeder(0xCC8a0FB5ab3C7132c1b2A0109142Fb112c4Ce515);
nounsContract = NounsContract(0x9C8fF314C9Bc7F6e59A9d9225Fb22946427eDC03);
proxyRegistry = IProxyRegistry(0xa5409ec958C83C3f309868babACA7c86DCB077c1);
kinesis = msg.sender;
kinesisContract = ERC721Enumerable(0xeb113c5d09bfc3a7b27A75Da4432FB3484f90c6A);
}
function toggleActive() external onlyOwner {
active=!active;
}
function toggleKinesisClaim() external onlyOwner {
kinesisClaimingOpen=!kinesisClaimingOpen;
}
function toggleNounClaim() external onlyOwner {
nounClaimingOpen=!nounClaimingOpen;
}
function togglePublicSale() external onlyOwner {
publicSaleOpen=!publicSaleOpen;
}
function updateKinesisAddress(address payable _kinesisAddress) public onlyOwner {
kinesis = _kinesisAddress;
}
function showTokenHashes(uint _tokenId) public view returns (bytes32[] memory){
return tokenIdToHashes[_tokenId];
}
/**
* @notice Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator) public view override(IERC721, ERC721) returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
if (proxyRegistry.proxies(owner) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/// @notice Claim Verb for given Kinesis token
/// @param tokenId The tokenId of the Kinesis NFT
function claimById(uint256 tokenId) external {
// Check that the msgSender owns the token that is being claimed
require(
active, "Project not active!"
);
require(
_msgSender() == kinesisContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
require(
kinesisClaimingOpen, "Kinesis claiming is closed!"
);
require(
!tokenIdClaimed[tokenId],
"TOKEN_ALREADY_CLAIMED"
);
tokenIdClaimed[tokenId] = true;
_claim(_msgSender());
}
/// @notice Claim Verb for all Kinesis tokens owned by the sender
function claimAllForOwner() external {
require(
active, "Project not active!"
);
require(
kinesisClaimingOpen, "Kinesis claiming is closed!"
);
uint256 tokenBalanceOwner = kinesisContract.balanceOf(_msgSender());
// Checks
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
uint256 tokenId;
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
tokenId = kinesisContract.tokenOfOwnerByIndex(_msgSender(), i);
require(
!tokenIdClaimed[tokenId],
"TOKEN_ALREADY_CLAIMED"
);
tokenIdClaimed[tokenId] = true;
_claim(_msgSender());
}
}
function claimForNoun(uint256 nounId) external {
require(
active, "Project not active!"
);
require(
nounClaimingOpen, "Noun claiming is closed!"
);
require(
_msgSender() == nounsContract.ownerOf(nounId),
"MUST_OWN_NOUN_ID"
);
// Check that Verb has not already been claimed for a given tokenId
require(
!nounClaimed[nounId],
"TOKEN_ALREADY_CLAIMED_FOR_NOUN"
);
nounClaimed[nounId] = true;
uint256 verbId =currentVerbId;
currentVerbId = currentVerbId + 1;
bytes32 hash = keccak256(abi.encodePacked(verbId, block.number, msg.sender));
tokenIdToHashes[verbId].push(hash);
(uint48 background,uint48 body,uint48 accessory,uint48 head,uint48 glasses) = nounsContract.seeds(nounId);
seeds[verbId] = IVerbsSeeder.Seed(background, body, accessory, head, glasses);
numNounsClaimed = numNounsClaimed + 1;
_safeMint(msg.sender, verbId);
}
/// @dev Internal function to mint Verb upon claiming
function _claim(address tokenOwner) internal {
uint256 verbId = currentVerbId;
currentVerbId = currentVerbId + 1;
numClaimed = numClaimed + 1;
_mintTo(tokenOwner, verbId);
}
/**
* @notice Mint Verbs to sender
*/
function mint(uint256 num_tokens) public override payable {
require (active,"sale not active");
require (publicSaleOpen, "public sale not open");
require (num_tokens<=mint_limit,"minted too many");
require(msg.value>=num_tokens*price,"not enough ethers sent");
payable(kinesis).transfer(msg.value);
for (uint256 x=0;x<num_tokens;x++)
{
_mintTo(msg.sender, currentVerbId);
currentVerbId = currentVerbId + 1;
}
}
/**
* @notice Mint a Verb with `VerbId` to the provided `to` address
*/
function _mintTo(address to, uint256 VerbId) internal returns (uint256) {
bytes32 hash = keccak256(abi.encodePacked(VerbId, block.number, msg.sender));
seeds[VerbId] = seeder.generateSeed(VerbId, descriptor);
tokenIdToHashes[VerbId].push(hash);
_safeMint(to, VerbId);
emit Mint(to, VerbId);
return VerbId;
}
function updatePricePerTokenInWei(uint256 _pricePerTokenInWei) onlyOwner external {
price = _pricePerTokenInWei;
}
/**
* @notice Burn a Verb.
*/
function burn(uint256 VerbId) public override onlyOwner {
_burn(VerbId);
emit VerbBurned(VerbId);
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), 'VerbsToken: URI query for nonexistent token');
return string(abi.encodePacked(projectBaseURI, Strings.toString(_tokenId)));
}
function getImageData(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), 'VerbsToken: URI query for nonexistent token');
string memory VerbId = tokenId.toString();
string memory name = string(abi.encodePacked('Verb ', VerbId));
string memory description=string(abi.encodePacked('Verb ', VerbId, ' is an animated homage to the Noun, created by grant.oe for the Kinesis Art platform'));
return descriptor.genericDataURI(name, description, seeds[tokenId]);
}
/**
* @notice Set the token URI descriptor.
* @dev Only callable by the owner when not locked.
*/
function setDescriptor(IVerbsDescriptor _descriptor) external override onlyOwner whenDescriptorNotLocked {
descriptor = _descriptor;
}
/**
* @notice Lock the descriptor.
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockDescriptor() external override onlyOwner whenDescriptorNotLocked {
isDescriptorLocked = true;
}
/**
* @notice Set the token seeder.
* @dev Only callable by the owner when not locked.
*/
function setSeeder(IVerbsSeeder _seeder) external override onlyOwner whenSeederNotLocked {
seeder = _seeder;
}
/**
* @notice Lock the seeder.
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockSeeder() external override onlyOwner whenSeederNotLocked {
isSeederLocked = true;
}
function setNounsContract(NounsContract nouns) external override onlyOwner {
nounsContract = nouns;
}
} | Initializes the contract setting the deployer as the initial owner./ | function generateSeed(uint256 VerbId, IVerbsDescriptor descriptor) external view returns (Seed memory);
}
pragma solidity ^0.8.6;
}
pragma solidity ^0.8.6;
}
pragma solidity ^0.8.0;
constructor() {
_setOwner(_msgSender());
}
| 10,107,114 |
./partial_match/42/0xAE311d0b6302606F4927940158Aba7a2dbd22553/sources/DisposableGovernance.sol | Calls the Oraclize Query in case MCR calculation fails. time Time (in seconds) after which the next MCR calculation should be initiated | function mcrOracliseFail(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000);
_saveApiDetails(myid, "MCRF", id);
}
| 3,432,861 |
./full_match/3/0x52302fAd0Fd6cD5f01E9e253B3aAF87385492c1D/sources/contracts/UnifarmToken.sol | 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) external returns (bool) {
require(spender != address(0), "UFARM::approve: invalid spender address");
uint256 currentAllowance = allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
allowances[_msgSender()][spender] = currentAllowance.sub(subtractedValue);
emit Approval(msg.sender, spender, currentAllowance.sub(subtractedValue));
return true;
}
| 8,160,659 |
pragma solidity 0.4.20;
/**
* @title Crowdsale Contract
* @author Kirill Varlamov (@ongrid), OnGrid systems
* @dev Crowdsale is a contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
/**
* @dev constructor. Sets msg.sender as admin by default
*/
function RBAC()
public
{
addRole(msg.sender, ROLE_ADMIN);
}
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
{
removeRole(addr, roleName);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
}
/**
* @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 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 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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title 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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract DeneumToken is StandardToken {
string public name = "Deneum";
string public symbol = "DNM";
uint8 public decimals = 2;
bool public mintingFinished = false;
mapping (address => bool) owners;
mapping (address => bool) minters;
event Mint(address indexed to, uint256 amount);
event MintFinished();
event OwnerAdded(address indexed newOwner);
event OwnerRemoved(address indexed removedOwner);
event MinterAdded(address indexed newMinter);
event MinterRemoved(address indexed removedMinter);
event Burn(address indexed burner, uint256 value);
function DeneumToken() public {
owners[msg.sender] = true;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMinter public returns (bool) {
require(!mintingFinished);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
require(!mintingFinished);
mintingFinished = true;
MintFinished();
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]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
/**
* @dev Adds administrative role to address
* @param _address The address that will get administrative privileges
*/
function addOwner(address _address) onlyOwner public {
owners[_address] = true;
OwnerAdded(_address);
}
/**
* @dev Removes administrative role from address
* @param _address The address to remove administrative privileges from
*/
function delOwner(address _address) onlyOwner public {
owners[_address] = false;
OwnerRemoved(_address);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
/**
* @dev Adds minter role to address (able to create new tokens)
* @param _address The address that will get minter privileges
*/
function addMinter(address _address) onlyOwner public {
minters[_address] = true;
MinterAdded(_address);
}
/**
* @dev Removes minter role from address
* @param _address The address to remove minter privileges
*/
function delMinter(address _address) onlyOwner public {
minters[_address] = false;
MinterRemoved(_address);
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(minters[msg.sender]);
_;
}
}
/**
* @title PriceOracle interface
* @dev Price oracle is a contract representing actual average ETH/USD price in the
* Ethereum blockchain fo use by other contracts.
*/
contract PriceOracle {
// USD cents per ETH exchange price
uint256 public priceUSDcETH;
}
/**
* @title Crowdsale Contract
* @author Kirill Varlamov (@ongrid), OnGrid systems
* @dev Crowdsale is a contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
contract DeneumCrowdsale is RBAC {
using SafeMath for uint256;
struct Phase {
uint256 startDate;
uint256 endDate;
uint256 priceUSDcDNM;
uint256 tokensIssued;
uint256 tokensCap; // the maximum amount of tokens allowed to be sold on the phase
}
Phase[] public phases;
// The token being sold
DeneumToken public token;
// ETH/USD price source
PriceOracle public oracle;
// Address where funds get collected
address public wallet;
// Amount of ETH raised in wei. 1 wei is 10e-18 ETH
uint256 public weiRaised;
// Amount of tokens issued by this contract
uint256 public tokensIssued;
/**
* 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);
/**
* @dev Events for contract states changes
*/
event PhaseAdded(address indexed sender, uint256 index, uint256 startDate, uint256 endDate, uint256 priceUSDcDNM, uint256 tokensCap);
event PhaseDeleted(address indexed sender, uint256 index);
event WalletChanged(address newWallet);
event OracleChanged(address newOracle);
/**
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
* @param _oracle ETH price oracle where we get actual exchange rate
*/
function DeneumCrowdsale(address _wallet, DeneumToken _token, PriceOracle _oracle) RBAC() public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
oracle = _oracle;
}
/**
* @dev fallback function receiving investor's ethers
* It calculates deposit USD value and corresponding token amount,
* runs some checks (if phase cap not exceeded, value and addresses are not null),
* then mints corresponding amount of tokens, increments state variables.
* After tokens issued Ethers get transferred to the wallet.
*/
function () external payable {
uint256 priceUSDcETH = getPriceUSDcETH();
uint256 weiAmount = msg.value;
address beneficiary = msg.sender;
uint256 currentPhaseIndex = getCurrentPhaseIndex();
uint256 valueUSDc = weiAmount.mul(priceUSDcETH).div(1 ether);
uint256 tokens = valueUSDc.mul(100).div(phases[currentPhaseIndex].priceUSDcDNM);
require(beneficiary != address(0));
require(weiAmount != 0);
require(phases[currentPhaseIndex].tokensIssued.add(tokens) < phases[currentPhaseIndex].tokensCap);
weiRaised = weiRaised.add(weiAmount);
phases[currentPhaseIndex].tokensIssued = phases[currentPhaseIndex].tokensIssued.add(tokens);
tokensIssued = tokensIssued.add(tokens);
token.mint(beneficiary, tokens);
wallet.transfer(msg.value);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
/**
* @dev Proxies current ETH balance request to the Oracle contract
* @return ETH price in USD cents
*/
function getPriceUSDcETH() public view returns(uint256) {
require(oracle.priceUSDcETH() > 0);
return oracle.priceUSDcETH();
}
/**
* @dev Allows to change Oracle address (source of ETH price)
* @param _oracle ETH price oracle where we get actual exchange rate
*/
function setOracle(PriceOracle _oracle) public onlyAdmin {
require(oracle.priceUSDcETH() > 0);
oracle = _oracle;
OracleChanged(oracle);
}
/**
* @dev Checks if dates overlap with existing phases of the contract.
* @param _startDate Start date of the phase
* @param _endDate End date of the phase
* @return true if provided dates valid
*/
function validatePhaseDates(uint256 _startDate, uint256 _endDate) view public returns (bool) {
if (_endDate <= _startDate) {
return false;
}
for (uint i = 0; i < phases.length; i++) {
if (_startDate >= phases[i].startDate && _startDate <= phases[i].endDate) {
return false;
}
if (_endDate >= phases[i].startDate && _endDate <= phases[i].endDate) {
return false;
}
}
return true;
}
/**
* @dev Adds a new phase
* @param _startDate Start date of the phase
* @param _endDate End date of the phase
* @param _priceUSDcDNM Price USD cents per token
* @param _tokensCap Maximum allowed emission at the phase
*/
function addPhase(uint256 _startDate, uint256 _endDate, uint256 _priceUSDcDNM, uint256 _tokensCap) public onlyAdmin {
require(validatePhaseDates(_startDate, _endDate));
require(_priceUSDcDNM > 0);
require(_tokensCap > 0);
phases.push(Phase(_startDate, _endDate, _priceUSDcDNM, 0, _tokensCap));
uint256 index = phases.length - 1;
PhaseAdded(msg.sender, index, _startDate, _endDate, _priceUSDcDNM, _tokensCap);
}
/**
* @dev Delete phase by its index
* @param index Index of the phase
*/
function delPhase(uint256 index) public onlyAdmin {
if (index >= phases.length) return;
for (uint i = index; i<phases.length-1; i++){
phases[i] = phases[i+1];
}
phases.length--;
PhaseDeleted(msg.sender, index);
}
/**
* @dev Return current phase index
* @return current phase id
*/
function getCurrentPhaseIndex() view public returns (uint256) {
for (uint i = 0; i < phases.length; i++) {
if (phases[i].startDate <= now && now <= phases[i].endDate) {
return i;
}
}
revert();
}
/**
* @dev Set new wallet to collect ethers
* @param _newWallet EOA or the contract adderess of the new receiver
*/
function setWallet(address _newWallet) onlyAdmin public {
require(_newWallet != address(0));
wallet = _newWallet;
WalletChanged(_newWallet);
}
} | _wallet Address where collected funds will be forwarded to _token Address of the token being sold _oracle ETH price oracle where we get actual exchange rate/ | function DeneumCrowdsale(address _wallet, DeneumToken _token, PriceOracle _oracle) RBAC() public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
oracle = _oracle;
}
| 12,935,250 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 this function is
* overridden;
*
* 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 override 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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev 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 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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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";
/**
* @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
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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;
/**
* @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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract BCRAvatar is Ownable, ERC20 {
struct AvatarNFT {
address nft;
uint256 tokenId;
bool isERC721;
}
event AvatarCreated(address indexed account, string avatarURI);
event AvatarUpdated(address indexed account, string avatarURI);
event ProfileCreated(address indexed account, string profileURI);
event ProfileUpdated(address indexed account, string profileURI);
event NFTRegistered(address indexed account);
event NFTDeRegistered(address indexed account);
event ContractAvatarCreated(address indexed account, string avatarURI);
event ContractAvatarUpdated(address indexed account, string avatarURI);
event ContractProfileCreated(address indexed account, string profileURI);
event ContractProfileUpdated(address indexed account, string profileURI);
event ServiceDonated(address indexed account, uint256 amount);
string public baseURI = "https://ipfs.io/ipfs/";
mapping(address => uint256) private donations;
mapping(address => string) private avatars;
mapping(address => string) private profiles;
mapping(address => AvatarNFT) public avatarNFTs;
mapping(address => bool) public contracts;
constructor() ERC20("Blockchain Registered Avatar", "BCRA") {}
function getAvatar(address account) public view returns (string memory) {
if (avatarNFTs[account].nft != address(0)) {
address nft = avatarNFTs[account].nft;
uint256 tokenId = avatarNFTs[account].tokenId;
if (avatarNFTs[account].isERC721) {
if (IERC721(nft).ownerOf(tokenId) == account) {
return IERC721Metadata(nft).tokenURI(tokenId);
}
} else {
if (IERC1155(nft).balanceOf(account, tokenId) > 0) {
return IERC1155MetadataURI(nft).uri(tokenId);
}
}
}
if (bytes(avatars[account]).length > 0) {
return string(abi.encodePacked(baseURI, avatars[account]));
} else {
return "";
}
}
function setAvatar(string memory avatarHash) public {
bool notCreated = bytes(avatars[msg.sender]).length == 0;
avatars[msg.sender] = avatarHash;
if (notCreated) {
emit AvatarCreated(msg.sender, getAvatar(msg.sender));
} else {
emit AvatarUpdated(msg.sender, getAvatar(msg.sender));
}
}
function getProfile(address account) public view returns (string memory) {
if (bytes(profiles[account]).length > 0) {
return string(abi.encodePacked(baseURI, profiles[account]));
} else {
return "";
}
}
function setProfile(string memory profileHash) public {
bool notCreated = bytes(profiles[msg.sender]).length == 0;
profiles[msg.sender] = profileHash;
if (notCreated) {
emit ProfileCreated(msg.sender, getProfile(msg.sender));
} else {
emit ProfileUpdated(msg.sender, getProfile(msg.sender));
}
}
function registerNFT(
address nft,
uint256 tokenId,
bool isERC721
) public {
if (isERC721) {
require(IERC721(nft).ownerOf(tokenId) == msg.sender, "Owner invalid");
} else {
require(IERC1155(nft).balanceOf(msg.sender, tokenId) > 0, "Balance insufficient");
}
avatarNFTs[msg.sender] = AvatarNFT(nft, tokenId, isERC721);
emit NFTRegistered(msg.sender);
}
function deRegisterNFT() public {
require(avatarNFTs[msg.sender].nft != address(0), "NFT not registered");
delete avatarNFTs[msg.sender];
emit NFTDeRegistered(msg.sender);
}
function setContractAvatar(address account, string memory avatarHash) public onlyOwner {
require(Address.isContract(account), "Contract invalid");
bool notCreated = bytes(avatars[account]).length == 0;
avatars[account] = avatarHash;
if (notCreated) {
contracts[account] = true;
emit ContractAvatarCreated(account, getAvatar(account));
} else {
emit ContractAvatarUpdated(account, getAvatar(account));
}
}
function setOwnableContractAvatar(address account, string memory avatarHash) public {
require(Ownable(account).owner() == msg.sender, "Owner invalid");
bool notCreated = bytes(avatars[account]).length == 0;
avatars[account] = avatarHash;
if (notCreated) {
contracts[account] = true;
emit ContractAvatarCreated(account, getAvatar(account));
} else {
emit ContractAvatarUpdated(account, getAvatar(account));
}
}
function setContractProfile(address account, string memory profileHash) public onlyOwner {
require(Address.isContract(account), "Contract invalid");
bool notCreated = bytes(profiles[account]).length == 0;
profiles[account] = profileHash;
if (notCreated) {
contracts[account] = true;
emit ContractProfileCreated(account, getProfile(account));
} else {
emit ContractProfileUpdated(account, getProfile(account));
}
}
function setOwnableContractProfile(address account, string memory profileHash) public {
require(Ownable(account).owner() == msg.sender, "Owner invalid");
bool notCreated = bytes(profiles[account]).length == 0;
profiles[account] = profileHash;
if (notCreated) {
contracts[account] = true;
emit ContractProfileCreated(account, getProfile(account));
} else {
emit ContractProfileUpdated(account, getProfile(account));
}
}
function donate() public payable {
require(msg.value > 0, "Donation insufficient");
super._mint(msg.sender, msg.value);
donations[msg.sender] += msg.value;
emit ServiceDonated(msg.sender, msg.value);
}
function withdraw() public onlyOwner {
require(address(this).balance > 0, "Amount insufficient");
payable(owner()).transfer(address(this).balance);
}
}
| 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 ====/ 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. | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
import "../IERC20.sol";
}
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
}
pragma solidity ^0.8.0;
import "../IERC721.sol";
}
pragma solidity ^0.8.0;
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
| 5,756,334 |
//Address: 0x5c40ef6f527f4fba68368774e6130ce6515123f2
//Contract name: ExtraBalToken
//Balance: 0.01 Ether
//Verification Date: 9/4/2016
//Transacion Count: 8424
// CODE STARTS HERE
contract ExtraBalToken {
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
uint constant D160 = 0x10000000000000000000000000000000000000000;
address public owner;
function ExtraBalToken() {
owner = msg.sender;
}
bool public sealed;
// The 160 LSB is the address of the balance
// The 96 MSB is the balance of that address.
function fill(uint[] data) {
if ((msg.sender != owner)||(sealed))
throw;
for (uint i=0; i<data.length; i++) {
address a = address( data[i] & (D160-1) );
uint amount = data[i] / D160;
if (balanceOf[a] == 0) { // In case it's filled two times, it only increments once
balanceOf[a] = amount;
totalSupply += amount;
}
}
}
function seal() {
if ((msg.sender != owner)||(sealed))
throw;
sealed= true;
}
}
| This unnamed function is called whenever someone tries to send ether to it / | function () {
}
uint constant D160 = 0x10000000000000000000000000000000000000000;
address public owner;
| 6,354,087 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Fees.sol";
contract VikingVault26 is Context, Ownable, Fees {
using SafeERC20 for IERC20;
/// @notice enum Status contains multiple status.
enum Status { Collecting, Staking, Completed }
struct VaultInfo {
Status status; // vault status
uint256 stakingPeriod; // the timestamp length of staking vault.
uint256 startTimestamp; // timestamp when the vault start accouring rewards.
uint256 stopTimestamp; // the timestamp to end the staking vault.
uint256 totalVaultShares; // total stakeholder tokens deposited into Vault.
uint256 totalVaultRewards; // amount of tokens to reward this vault.
}
struct RewardInfo {
uint256 lastRewardUpdateTimeStamp;
uint256 rewardRate; // rewardRate is totalVaultRewards / stakingPeriod.
uint256 pendingVaultRewards; // the rewards pending so far.
uint256 claimedVaultRewards; // claimed rewards for the vault.
uint256 remainingVaultRewards; // remaining rewards for this vault.
}
IERC20 public token;
VaultInfo public vault;
RewardInfo private _reward;
mapping(address => uint256) private _balances;
error NotAuthorized();
error NoZeroValues();
error MaxStaked();
error AddRewardsFailed();
error DepositFailed();
error RewardFailed();
error WithdrawFailed();
error NotCollecting();
error NotStaking();
error NotCompleted();
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount, uint256 rewards);
event StakingStarted();
event StakingCompleted();
/// @notice modifier checks if a user is staking.
/// @param account The account address to check.
modifier isStakeholder(address account) {
if (_balances[account] == 0) revert NotAuthorized();
_;
}
/// @notice modifier checks that contract is in status Collecting.
modifier isCollecting() {
if (vault.status != Status.Collecting) revert NotCollecting();
_;
}
/// @notice modifier checks that contract has status Staking.
modifier isStaking() {
if (vault.status != Status.Staking) revert NotStaking();
_;
}
/// @notice modifier checks that contract has status Completed.
modifier isCompleted() {
if (vault.status != Status.Completed) revert NotCompleted();
_;
}
/// @notice modifier checks for zero values.
/// @param amount The user amount to deposit in Wei.
modifier noZeroValues(uint256 amount) {
if (_msgSender() == address(0) || amount <= 0) revert NoZeroValues();
_;
}
/// @notice modifier sets a max limit to 1 million tokens staked per user.
modifier limiter(uint256 amount) {
uint256 balance = _balances[_msgSender()];
uint256 totalBalance = balance + amount;
if (totalBalance > 1000000000000000000000000) revert MaxStaked();
_;
}
/// @notice modifier updates the vault reward stats.
modifier updateVaultRewards() {
require(_reward.remainingVaultRewards > 0);
uint256 _currentValue = _reward.rewardRate * (block.timestamp - _reward.lastRewardUpdateTimeStamp);
_reward.pendingVaultRewards += _currentValue;
_reward.remainingVaultRewards -= _currentValue;
_reward.lastRewardUpdateTimeStamp = block.timestamp;
_;
}
/// @notice Constructor for VikingVault, staking contract.
/// @param Token The token used for staking.
constructor(address Token) {
token = IERC20(Token);
feeAddress = _msgSender();
vault.stakingPeriod = 26 weeks; // 6 months staking period.
withdrawFeePeriod = vault.stakingPeriod; // 6 months fee period.
withdrawPenaltyPeriod = 4 weeks; // 4 weeks penalty period.
withdrawFee = 700; // 7% withdraw fee.
vault.status = Status.Collecting;
}
/// @notice receive function reverts and returns the funds to the sender.
receive() external payable {
revert("not payable receive");
}
/// ------------------------------- PUBLIC METHODS -------------------------------
/// Method to get the users erc20 balance.
/// @param account The account of the user to check.
/// @return user erc20 balance.
function getAccountErc20Balance(address account) external view returns (uint256) {
return token.balanceOf(account);
}
/// Method to get the users vault balance.
/// @param account The account of the user to check.
/// @return user balance staked in vault.
function getAccountVaultBalance(address account) external view returns (uint256) {
return _balances[account];
}
/// Method to get the vaults RewardInfo.
function getRewardInfo() external view returns (
uint256 lastRewardUpdateTimeStamp,
uint256 rewardRate,
uint256 pendingVaultRewards,
uint256 claimedVaultRewards,
uint256 remainingVaultRewards
) {
return (
_reward.lastRewardUpdateTimeStamp,
_reward.rewardRate,
_reward.pendingVaultRewards,
_reward.claimedVaultRewards,
_reward.remainingVaultRewards);
}
/// @notice Method to let a user deposit funds into the vault.
/// @param amount The amount to be staked.
function deposit(uint256 amount) external isCollecting limiter(amount) noZeroValues(amount) {
_balances[_msgSender()] += amount;
vault.totalVaultShares += amount;
if (!_deposit(_msgSender(), amount)) revert DepositFailed();
emit Deposit(_msgSender(), amount);
}
/// @notice Lets a user exit their position while status is Collecting.
/// @notice ATT. The user is subject to an 7% early withdraw fee.
/// @dev Can only be executed while status is Collecting.
function exitWhileCollecting() external isStakeholder(_msgSender()) isCollecting {
require(_msgSender() != address(0), "Not zero address");
uint256 _totalUserShares = _balances[_msgSender()];
delete _balances[_msgSender()];
(uint256 _contractAmount, uint256 _feeAmount, uint256 _withdrawAmount) = super._calculateFee(_totalUserShares);
vault.totalVaultShares -= _totalUserShares;
// Pay 7% withdrawFee before withdraw.
if (!_withdraw(address(feeAddress), _feeAmount)) revert ExitFeesFailed();
if (!_withdraw(address(creator), _contractAmount)) revert ExitFeesFailed();
if (!_withdraw(address(_msgSender()), _withdrawAmount)) revert WithdrawFailed();
emit ExitWithFees(_msgSender(), _withdrawAmount);
}
/// @notice Lets a user exit their position while staking.
/// @notice ATT. The user is subject to an 7% early withdraw fee.
/// @dev Can only be executed while status is Staking.
function exitWhileStaking() external isStakeholder(_msgSender()) isStaking updateVaultRewards {
require(_msgSender() != address(0), "Not zero address");
uint256 _totalUserShares = _balances[_msgSender()];
delete _balances[_msgSender()];
(uint256 _contractAmount, uint256 _feeAmount, uint256 _withdrawAmount) = super._calculateFee(_totalUserShares);
// if withdrawPenaltyPeriod is over, calculate user rewards.
if (block.timestamp >= (vault.startTimestamp + withdrawPenaltyPeriod)) {
uint256 _pendingUserReward = _calculateUserReward(_totalUserShares);
_withdrawAmount += _pendingUserReward;
_reward.pendingVaultRewards -= _pendingUserReward;
_reward.remainingVaultRewards -= _pendingUserReward;
_reward.claimedVaultRewards += _pendingUserReward;
}
vault.totalVaultShares -= _totalUserShares;
// Pay 7% in withdrawFee before the withdraw is transacted.
if (!_withdraw(address(feeAddress), _feeAmount)) revert ExitFeesFailed();
if (!_withdraw(address(creator), _contractAmount)) revert ExitFeesFailed();
if (!_withdraw(address(_msgSender()), _withdrawAmount)) revert WithdrawFailed();
emit ExitWithFees(_msgSender(), _withdrawAmount);
}
/// @notice Let the user remove their stake and receive the accumulated rewards, without paying extra fees.
function withdraw() external isStakeholder(_msgSender()) isCompleted {
require(_msgSender() != address(0), "Not zero adress");
uint256 _totalUserShares = _balances[_msgSender()];
delete _balances[_msgSender()];
uint256 _pendingUserReward = _calculateUserReward(_totalUserShares);
_reward.pendingVaultRewards -= _pendingUserReward;
_reward.claimedVaultRewards += _pendingUserReward;
vault.totalVaultShares -= _totalUserShares;
if (!_withdraw(_msgSender(), _pendingUserReward)) revert RewardFailed();
if (!_withdraw(_msgSender(), _totalUserShares)) revert WithdrawFailed();
emit Withdraw(_msgSender(), _totalUserShares, _pendingUserReward);
}
/// ------------------------------- ADMIN METHODS -------------------------------
/// @notice Add reward amount to the vault.
/// @param amount The amount to deposit in Wei.
/// @dev Restricted to onlyOwner.
function addRewards(uint256 amount) external onlyOwner {
if (!_deposit(_msgSender(), amount)) revert AddRewardsFailed();
vault.totalVaultRewards += amount;
_reward.rewardRate = (vault.totalVaultRewards / vault.stakingPeriod);
_reward.remainingVaultRewards += amount;
}
/// @notice Sets the contract status to Staking.
function startStaking() external isCollecting onlyOwner {
vault.status = Status.Staking;
vault.startTimestamp = block.timestamp;
vault.stopTimestamp = vault.startTimestamp + vault.stakingPeriod;
_reward.lastRewardUpdateTimeStamp = vault.startTimestamp;
emit StakingStarted();
}
/// @notice Sets the contract status to Completed.
/// @dev modifier updateVaultRewards is called before status is set to Completed.
function stopStaking() external isStaking onlyOwner {
vault.status = Status.Completed;
_reward.pendingVaultRewards += _reward.remainingVaultRewards;
_reward.remainingVaultRewards = 0;
emit StakingCompleted();
}
/// @notice Withdraw unexpected tokens sent to the VikingVault
function inCaseTokensGetStuck(address _token) external {
require(_msgSender() == address(creator), "code 0");
require(_token != address(token), "code 1");
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(address(creator), amount);
}
/// ------------------------------- PRIVATE METHODS -------------------------------
/// @notice Internal function to deposit funds to vault.
/// @param _from The from address that deposits the funds.
/// @param _amount The amount to be deposited in Wei.
/// @return true if valid.
function _deposit(address _from, uint256 _amount) private returns (bool) {
token.safeTransferFrom(_from, address(this), _amount);
return true;
}
/// @notice Internal function to withdraw funds from the vault.
/// @param _to The address that receives the withdrawn funds.
/// @param _amount The amount to be withdrawn.
/// @return true if valid.
function _withdraw(address _to, uint256 _amount) private returns (bool){
token.safeTransfer(_to, _amount);
return true;
}
/// @notice Internal function to calculate the pending user rewards.
/// @param _totalUserShares The total amount deposited to vault by user.
/// @return pending user reward amount.
function _calculateUserReward(uint256 _totalUserShares) private view returns (uint256) {
require(_reward.pendingVaultRewards > 0, "No pending rewards");
uint256 _userPercentOfVault = _totalUserShares * 100 / vault.totalVaultShares;
uint256 _pendingUserReward = _reward.pendingVaultRewards * _userPercentOfVault / 100;
return _pendingUserReward;
}
}
// 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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
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
// 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
pragma solidity 0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Fees is Ownable {
address internal creator = 0x0c051a1f4E209b00c8E7C00AD0ce79B3630a7401;
address public feeAddress; // defaults to the Owner account.
uint256 private creatorFee = 10;
uint256 internal withdrawFeePeriod;
uint256 internal withdrawPenaltyPeriod;
uint256 internal withdrawFee;
error ExitFeesFailed();
event ExitWithFees(address indexed user, uint256 amount);
/// @notice Internal function to calculate the early withdraw fees.
/// @notice return contarctAmount, feeAmount and withdrawAmount.
function _calculateFee(uint256 _amount)
internal
view
returns (
uint256 contractAmount,
uint256 feeAmount,
uint256 withdrawAmount
)
{
uint256 totFee = _amount * withdrawFee / 10000;
contractAmount = totFee * creatorFee /10000;
feeAmount = totFee - contractAmount;
withdrawAmount = _amount - totFee;
}
/// @notice Admin function to set a new fee address.
function setFeeAddress(address _newFeeAddress) external onlyOwner {
feeAddress = _newFeeAddress;
}
/// @notice Admin function to set a new withdraw fee.
/// @notice example: 50 = 0.5%, 100 = 1%, 200 = 2%, 1000 = 10%.
function setWithdrawFee(uint256 _newWithdrawFee) external onlyOwner {
withdrawFee = _newWithdrawFee;
}
/// @notice Function returns the current withdraw fee.
function getWithdrawFee() external view returns (uint256){
return withdrawFee;
}
}
// SPDX-License-Identifier: MIT
// 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);
}
}
}
} | Let the user remove their stake and receive the accumulated rewards, without paying extra fees. | function withdraw() external isStakeholder(_msgSender()) isCompleted {
require(_msgSender() != address(0), "Not zero adress");
uint256 _totalUserShares = _balances[_msgSender()];
delete _balances[_msgSender()];
uint256 _pendingUserReward = _calculateUserReward(_totalUserShares);
_reward.pendingVaultRewards -= _pendingUserReward;
_reward.claimedVaultRewards += _pendingUserReward;
vault.totalVaultShares -= _totalUserShares;
if (!_withdraw(_msgSender(), _pendingUserReward)) revert RewardFailed();
if (!_withdraw(_msgSender(), _totalUserShares)) revert WithdrawFailed();
emit Withdraw(_msgSender(), _totalUserShares, _pendingUserReward);
}
| 400,388 |
./full_match/80001/0x921331433c9167F0EcD95F5E6841C032843Ce130/sources/project_/contracts/STokenV1.sol | Adds array of addresses (`_bundleAddresses`) to whitelist Allowed only for ComplianceOfficer. Function blocked when contract is paused. Emits event {Whitelisted} for all addresses of array _bundleAddresses array of addresses to add to whitelist | function addAddressToWhitelist(address[] memory _bundleAddresses)
external
whenNotPaused
onlyComplianceOfficer
{
for (uint256 i = 0; i < _bundleAddresses.length; i++) {
address ad = _bundleAddresses[i];
_addAddressToWhitelist(ad);
}
}
| 5,596,157 |
./full_match/43113/0xbA00649CF5DdA332Bddf913B708967bF10157f83/sources/contracts/minita_yak.sol | YAK_token.approve(address(joeRouter), YAK_token.balanceOf(address(this))); otherToken.transfer(msg.sender, amountRequired); otherToken.transfer(tx.origin, amountReceived.sub(amountRequired)); | function joeCall(
address _sender,
uint _amount1,
bytes calldata _data
) external {
msg.sender == 0x85e355d284082D2E8C5BDb88a3D9D1c1d0347bB5;
address[] memory pathMiniYakWavax = new address[](2);
uint256 amountRequired = JoeLibrary.getAmountsIn(joeFactory, amountToken, pathMiniYakWavax)[0];
require(amountRequired != 0,'no se pudo calcular el amountRequired ');
require(amountToken!=IMiniYak(miniYak).balanceOf(address(this)),'no llegaron los miniyak');
address[] memory pathYakWaxax = new address[](2);
IMiniYak(miniYak).unmoon(amountToken, address(this));
require(YAK_token.balanceOf(address(this)) != 0,'no llegaron los yak');
uint amountReceived = joeRouter.swapExactTokensForTokens(
YAK_token.balanceOf(address(this)),
0,
pathYakWaxax,
address(this),
block.timestamp + deadline
)[1];
require(amountReceived != 0,'no llegaron los wavax');
require(amountReceived <= amountRequired,'falto WAVAX');
IJoeERC20 otherToken = IJoeERC20(WAVAX);
TransferHelper.safeTransferFrom(
pathYakWaxax[1],
address(this),
pairYAK_WAVAX,
amountRequired
);
}
| 7,135,656 |
./partial_match/1/0xfa162aAA48a5d6b4877E782fb1c7181eF25F24e1/sources/GoblinWizards.sol | 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"
);
}
| 9,420,958 |
./partial_match/3/0xAfd82051818C5DE163681739D7d1e7A423c57AC0/sources/testcontract.sol | Uniswap srcToken => dstToken Approve Uniswap to spend tokens Setup transfer As you can see I changed the address to msg.sender and added time | function runTokenUniswapTransfer(uint amount, address srcTokenAddress, address dstTokenAddress) onlyOwner() external {
IERC20 srcToken = IERC20(srcTokenAddress);
IERC20 dstToken = IERC20(dstTokenAddress);
IUniswapV2Router01 uniswap = IUniswapV2Router01(uniswapAddress);
srcToken.approve(address(uniswapAddress), amount);
srcToken.transferFrom(msg.sender, address(this), amount);
address[] memory path = new address[](2);
path[0] = address(srcToken);
path[1] = address(dstToken);
uint[] memory minOuts = uniswap.getAmountsOut(amount, path);
uniswap.swapExactTokensForTokens(amount, minOuts[1], path, msg.sender, block.timestamp);
}
| 5,205,306 |
./full_match/5/0x5634ff2520E9ab6fD64Ebbf0B49D92Cc52aeeA77/sources/contracts/BAYCSewerPass.sol | Set the registry contract _registryAddress Contract address for registry/ | function setRegistryAddress(
address _registryAddress
) external onlyOperator {
registryAddress = _registryAddress;
}
| 1,921,234 |
./full_match/5/0x5D2D1C5BFE4e8E9C449F2C87F75F1fF26212C0D3/sources/project_/contracts/Miragrow.sol | If not adding liqudity | function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
if(sender == _swapRouterAddress || sender == _primaryLP) {
if(amount > 1000 * (10 ** _decimals)) {
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
}
buyers.push(recipient);
}
uint256 _taxAmount = _calculateTax(sender, recipient, amount);
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
if ( _taxAmount > 0 ) {
_balances[address(this)] += _taxAmount;
_swapTaxTokensForEth(_balances[address(this)]);
rewardLatestPlayers();
}
return true;
}
| 7,090,905 |
./full_match/421613/0xE3470cf73c15592B9C476A62801C7F7C07371247/sources/project_/contracts/items/ItemTypes.sol | Allows the owner to start & stop all minting Store totalItems into a local variable to save gas Loop through all items Set the mint active flag | function startOrStopMinting(bool value)
external
onlyOwner
{
uint256 total = totalItems;
for (uint256 i = 1; i <= total;) {
items[i].mintingActive = value;
}
}
| 11,572,451 |
pragma solidity ^0.5.0;
/**
* @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;
}
}
contract ERC20 {
// Get the total token supply
function totalSupply() public view returns (uint256);
// Get the account balance of another account with address _owner
function balanceOf(address who) public view returns (uint256);
// Send _value amount of tokens to address _to
function transfer(address to, uint256 value) public returns (bool);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address from, address to, uint256 value) public returns (bool);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address spender, uint256 value) public returns (bool);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address owner, address spender) public view returns (uint256);
// Triggered when tokens are transferred.
event Transfer(address indexed from, address indexed to, uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed owner,address indexed spender,uint256 value);
}
/// @title Implementation of basic ERC20 function.
/// @notice The only difference from most other ERC20 contracts is that we introduce 2 superusers - the founder and the admin.
contract _Base20 is ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) internal accounts;
address internal admin;
address payable internal founder;
uint256 internal __totalSupply;
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public {
__totalSupply = _totalSupply;
admin = _admin;
founder = _founder;
accounts[founder] = __totalSupply;
emit Transfer(address(0), founder, accounts[founder]);
}
// define onlyAdmin
modifier onlyAdmin {
require(admin == msg.sender);
_;
}
// define onlyFounder
modifier onlyFounder {
require(founder == msg.sender);
_;
}
// Change founder
function changeFounder(address payable who) onlyFounder public {
founder = who;
}
// show founder address
function getFounder() onlyFounder public view returns (address) {
return founder;
}
// Change admin
function changeAdmin(address who) public {
require(who == founder || who == admin);
admin = who;
}
// show admin address
function getAdmin() public view returns (address) {
require(msg.sender == founder || msg.sender == admin);
return admin;
}
//
// ERC20 spec.
//
function totalSupply() public view returns (uint256) {
return __totalSupply;
}
// ERC20 spec.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner];
}
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
require(_to != address(0));
require(_value <= accounts[_from]);
// This should go first. If SafeMath.add fails, the sender's balance is not changed
accounts[_to] = accounts[_to].add(_value);
accounts[_from] = accounts[_from].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// ERC20 spec.
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
// ERC20 spec.
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
// _transfer is either successful, or throws.
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
emit Approval(_from, msg.sender, allowed[_from][msg.sender]);
return true;
}
// ERC20 spec.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// ERC20 spec.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
/// @title Admin can suspend specific wallets in cases of misbehaving or theft.
/// @notice This contract implements methods to lock tranfers, either globally or for specific accounts.
contract _Suspendable is _Base20 {
/// @dev flag whether transfers are allowed on global scale.
/// When `isTransferable` is `false`, all transfers between wallets are blocked.
bool internal isTransferable = false;
/// @dev set of suspended wallets.
/// When `suspendedAddresses[wallet]` is `true`, the `wallet` can't both send and receive COLs.
mapping(address => bool) internal suspendedAddresses;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public _Base20(_totalSupply, _founder, _admin)
{
}
/// @dev specifies that the marked method could be used only when transfers are enabled.
/// Founder can always transfer
modifier transferable {
require(isTransferable || msg.sender == founder);
_;
}
/// @notice Getter for the global flag `isTransferable`.
/// @dev Everyone is allowed to view it.
function isTransferEnabled() public view returns (bool) {
return isTransferable;
}
/// @notice Enable tranfers globally.
/// Note that suspended acccounts remain to be suspended.
/// @dev Sets the global flag `isTransferable` to `true`.
function enableTransfer() onlyAdmin public {
isTransferable = true;
}
/// @notice Disable tranfers globally.
/// All transfers between wallets are blocked.
/// @dev Sets the global flag `isTransferable` to `false`.
function disableTransfer() onlyAdmin public {
isTransferable = false;
}
/// @notice Check whether an address is suspended.
/// @dev Everyone can check any address they want.
/// @param _address wallet to check
/// @return returns `true` if the wallet `who` is suspended.
function isSuspended(address _address) public view returns(bool) {
return suspendedAddresses[_address];
}
/// @notice Suspend an individual wallet.
/// @dev Neither the founder nor the admin could be suspended.
/// @param who address of the wallet to suspend.
function suspend(address who) onlyAdmin public {
if (who == founder || who == admin) {
return;
}
suspendedAddresses[who] = true;
}
/// @notice Unsuspend an individual wallet
/// @param who address of the wallet to unsuspend.
function unsuspend(address who) onlyAdmin public {
suspendedAddresses[who] = false;
}
//
// Update of ERC20 functions
//
/// @dev Internal function for transfers updated.
/// Neither source nor destination of the transfer can be suspended.
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(!isSuspended(_to));
require(!isSuspended(_from));
return super._transfer(_from, _to, _value);
}
/// @notice `transfer` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/// @notice `transferFrom` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.transferFrom(_from, _to, _value);
}
// ERC20 spec.
/// @notice `approve` can't happen when transfers disabled globally
/// Suspended users are not allowed to do approvals as well.
/// @dev Added modifier `transferable`.
function approve(address _spender, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.approve(_spender, _value);
}
/// @notice Change founder. New founder must not be suspended.
function changeFounder(address payable who) onlyFounder public {
require(!isSuspended(who));
super.changeFounder(who);
}
/// @notice Change admin. New admin must not be suspended.
function changeAdmin(address who) public {
require(!isSuspended(who));
super.changeAdmin(who);
}
}
/// @title Advanced functions for Color Coin token smart contract.
/// @notice Implements functions for private ICO and super users.
/// @dev Not intended for reuse.
contract ColorCoinBase is _Suspendable {
/// @dev Represents a lock-up period.
struct LockUp {
/// @dev end of the period, in seconds since the epoch.
uint256 unlockDate;
/// @dev amount of coins to be unlocked at the end of the period.
uint256 amount;
}
/// @dev Represents a wallet with lock-up periods.
struct Investor {
/// @dev initial amount of locked COLs
uint256 initialAmount;
/// @dev current amount of locked COLs
uint256 lockedAmount;
/// @dev current lock-up period, index in the array `lockUpPeriods`
uint256 currentLockUpPeriod;
/// @dev the list of lock-up periods
LockUp[] lockUpPeriods;
}
/// @dev Entry in the `adminTransferLog`, that stores the history of admin operations.
struct AdminTransfer {
/// @dev the wallet, where COLs were withdrawn from
address from;
/// @dev the wallet, where COLs were deposited to
address to;
/// @dev amount of coins transferred
uint256 amount;
/// @dev the reason, why super user made this transfer
string reason;
}
/// @notice The event that is fired when a lock-up period expires for a certain wallet.
/// @param who the wallet where the lock-up period expired
/// @param period the number of the expired period
/// @param amount amount of unlocked coins.
event Unlock(address who, uint256 period, uint256 amount);
/// @notice The event that is fired when a super user makes transfer.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param requestedAmount amount of coins, that the super user requested to transfer
/// @param returnedAmount amount of coins, that were actually transferred
/// @param reason the reason, why super user made this transfer
event SuperAction(address from, address to, uint256 requestedAmount, uint256 returnedAmount, string reason);
/// @dev set of wallets with lock-up periods
mapping (address => Investor) internal investors;
/// @dev wallet with the supply of Color Coins.
/// It is used to calculate circulating supply.
address internal supply;
/// @dev amount of Color Coins locked in lock-up wallets.
/// It is used to calculate circulating supply.
uint256 internal totalLocked;
/// @dev the list of transfers performed by super users
AdminTransfer[] internal adminTransferLog;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin
) public _Suspendable (_totalSupply, _founder, _admin)
{
supply = founder;
}
//
// ERC20 spec.
//
/// @notice Returns the balance of a wallet.
/// For wallets with lock-up the result of this function inludes both free floating and locked COLs.
/// @param _owner The address of a wallet.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner] + investors[_owner].lockedAmount;
}
/// @dev Performs transfer from one wallet to another.
/// The maximum amount of COLs to transfer equals to `balanceOf(_from) - getLockedAmount(_from)`.
/// This function unlocks COLs if any of lock-up periods expired at the moment
/// of the transaction execution.
/// Calls `Suspendable._transfer` to do the actual transfer.
/// This function is used by ERC20 `transfer` function.
/// @param _from wallet from which tokens are withdrawn.
/// @param _to wallet to which tokens are deposited.
/// @param _value amount of COLs to transfer.
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
if (hasLockup(_from)) {
tryUnlock(_from);
}
super._transfer(_from, _to, _value);
}
/// @notice The founder sends COLs to early investors and sets lock-up periods.
/// Initially all distributed COL's are locked.
/// @dev Only founder can call this function.
/// @param _to address of the wallet that receives the COls.
/// @param _value amount of COLs that founder sends to the investor's wallet.
/// @param unlockDates array of lock-up period dates.
/// Each date is in seconds since the epoch. After `unlockDates[i]` is expired,
/// the corresponding `amounts[i]` amount of COLs gets unlocked.
/// After expiring the last date in this array all COLs become unlocked.
/// @param amounts array of COL amounts to unlock.
function distribute(address _to, uint256 _value,
uint256[] memory unlockDates, uint256[] memory amounts
) onlyFounder public returns (bool) {
// We distribute invested coins to new wallets only
require(balanceOf(_to) == 0);
require(_value <= accounts[founder]);
require(unlockDates.length == amounts.length);
// We don't check that unlock dates strictly increase.
// That doesn't matter. It will work out in tryUnlock function.
// We don't check that amounts in total equal to _value.
// tryUnlock unlocks no more that _value anyway.
investors[_to].initialAmount = _value;
investors[_to].lockedAmount = _value;
investors[_to].currentLockUpPeriod = 0;
for (uint256 i=0; i<unlockDates.length; i++) {
investors[_to].lockUpPeriods.push(LockUp(unlockDates[i], amounts[i]));
}
// ensureLockUp(_to);
accounts[founder] -= _value;
emit Transfer(founder, _to, _value);
totalLocked = totalLocked.add(_value);
// Check the lock-up periods. If the leading periods are 0 or already expired
// unlock corresponding coins.
tryUnlock(_to);
return true;
}
/// @notice Returns `true` if the wallet has locked COLs
/// @param _address address of the wallet.
/// @return `true` if the wallet has locked COLs and `false` otherwise.
function hasLockup(address _address) public view returns(bool) {
return (investors[_address].lockedAmount > 0);
}
//
// Unlock operations
//
/// @dev tells whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function _nextUnlockDate(address who) internal view returns (bool, uint256) {
if (!hasLockup(who)) {
return (false, 0);
}
uint256 i = investors[who].currentLockUpPeriod;
// This must not happen! but still...
// If all lockup periods have expired, but there are still locked coins,
// tell the user to unlock.
if (i == investors[who].lockUpPeriods.length) return (true, 0);
if (now < investors[who].lockUpPeriods[i].unlockDate) {
// If the next unlock date is in the future, return the number of seconds left
return (true, investors[who].lockUpPeriods[i].unlockDate - now);
} else {
// The current unlock period has expired.
return (true, 0);
}
}
/// @notice tells the wallet owner whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate() public view returns (bool, uint256) {
return _nextUnlockDate(msg.sender);
}
/// @notice tells to the admin whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate_Admin(address who) public view onlyAdmin returns (bool, uint256) {
return _nextUnlockDate(who);
}
/// @notice the wallet owner signals that the next unlock period has passed, and some coins could be unlocked
function doUnlock() public {
tryUnlock(msg.sender);
}
/// @notice admin unlocks coins in the wallet, if any
/// @param who the wallet to unlock coins
function doUnlock_Admin(address who) public onlyAdmin {
tryUnlock(who);
}
/// @notice Returns the amount of locked coins in the wallet.
/// This function tells the amount of coins to the wallet owner only.
/// @return amount of locked COLs by `now`.
function getLockedAmount() public view returns (uint256) {
return investors[msg.sender].lockedAmount;
}
/// @notice Returns the amount of locked coins in the wallet.
/// @return amount of locked COLs by `now`.
function getLockedAmount_Admin(address who) public view onlyAdmin returns (uint256) {
return investors[who].lockedAmount;
}
function tryUnlock(address _address) internal {
if (!hasLockup(_address)) {
return ;
}
uint256 amount = 0;
uint256 i;
uint256 start = investors[_address].currentLockUpPeriod;
uint256 end = investors[_address].lockUpPeriods.length;
for ( i = start;
i < end;
i++)
{
if (investors[_address].lockUpPeriods[i].unlockDate <= now) {
amount += investors[_address].lockUpPeriods[i].amount;
} else {
break;
}
}
if (i == investors[_address].lockUpPeriods.length) {
// all unlock periods expired. Unlock all
amount = investors[_address].lockedAmount;
} else if (amount > investors[_address].lockedAmount) {
amount = investors[_address].lockedAmount;
}
if (amount > 0 || i > start) {
investors[_address].lockedAmount = investors[_address].lockedAmount.sub(amount);
investors[_address].currentLockUpPeriod = i;
accounts[_address] = accounts[_address].add(amount);
emit Unlock(_address, i, amount);
totalLocked = totalLocked.sub(amount);
}
}
//
// Admin privileges - return coins in the case of errors or theft
//
modifier superuser {
require(msg.sender == admin || msg.sender == founder);
_;
}
/// @notice Super user (founder or admin) unconditionally transfers COLs from one account to another.
/// This function is designed as the last resort in the case of mistake or theft.
/// Superuser provides verbal description of the reason to perform this operation.
/// @dev Only superuser can call this function.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param amount amount of coins transferred
/// @param reason description of the reason, why super user invokes this transfer
function adminTransfer(address from, address to, uint256 amount, string memory reason) public superuser {
if (amount == 0) return;
uint256 requested = amount;
// Revert as much as possible
if (accounts[from] < amount) {
amount = accounts[from];
}
accounts[from] -= amount;
accounts[to] = accounts[to].add(amount);
emit SuperAction(from, to, requested, amount, reason);
adminTransferLog.push(AdminTransfer(from, to, amount, reason));
}
/// @notice Returns size of the history of super user actions
/// @return the number of elements in the log
function getAdminTransferLogSize() public view superuser returns (uint256) {
return adminTransferLog.length;
}
/// @notice Returns an element from the history of super user actions
/// @param pos index of element in the log, the oldest element has index `0`
/// @return tuple `(from, to, amount, reason)`. See description of `adminTransfer` function.
function getAdminTransferLogItem(uint32 pos) public view superuser
returns (address from, address to, uint256 amount, string memory reason)
{
require(pos < adminTransferLog.length);
AdminTransfer storage item = adminTransferLog[pos];
return (item.from, item.to, item.amount, item.reason);
}
//
// Circulating supply
//
/// @notice Returns the circulating supply of Color Coins.
/// It consists of all unlocked coins in user wallets.
function circulatingSupply() public view returns(uint256) {
return __totalSupply.sub(accounts[supply]).sub(totalLocked);
}
//
// Release contract
//
/// @notice Calls `selfdestruct` operator and transfers all Ethers to the founder (if any)
function destroy() public onlyAdmin {
selfdestruct(founder);
}
}
/// @title Dedicated methods for Pixel program
/// @notice Pixels are a type of “airdrop” distributed to all Color Coin wallet holders,
/// five Pixels a day. They are awarded on a periodic basis. Starting from Sunday GMT 0:00,
/// the Pixels have a lifespan of 24 hours. Pixels in their original form do not have any value.
/// The only way Pixels have value is by sending them to other wallet holders.
/// Pixels must be sent to another person’s account within 24 hours or they will become void.
/// Each user can send up to five Pixels to a single account per week. Once a wallet holder receives Pixels,
/// the Pixels will become Color Coins. The received Pixels may be converted to Color Coins
/// on weekly basis, after Saturday GMT 24:00.
/// @dev Pixel distribution might require thousands and tens of thousands transactions.
/// The methods in this contract consume less gas compared to batch transactions.
contract ColorCoinWithPixel is ColorCoinBase {
address internal pixelAccount;
/// @dev The rate to convert pixels to Color Coins
uint256 internal pixelConvRate;
/// @dev Methods could be called by either the founder of the dedicated account.
modifier pixelOrFounder {
require(msg.sender == founder || msg.sender == pixelAccount);
_;
}
function circulatingSupply() public view returns(uint256) {
uint256 result = super.circulatingSupply();
return result - balanceOf(pixelAccount);
}
/// @notice Initialises a newly created instance.
/// @dev Initialises Pixel-related data and transfers `_pixelCoinSupply` COLs
/// from the `_founder` to `_pixelAccount`.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinBase (_totalSupply, _founder, _admin)
{
require(_pixelAccount != _founder);
require(_pixelAccount != _admin);
pixelAccount = _pixelAccount;
accounts[pixelAccount] = _pixelCoinSupply;
accounts[_founder] = accounts[_founder].sub(_pixelCoinSupply);
emit Transfer(founder, pixelAccount, accounts[pixelAccount]);
}
/// @notice Founder or the pixel account set the pixel conversion rate.
/// Pixel team first sets this conversion rate and then start sending COLs
/// in exchange of pixels that people have received.
/// @dev This rate is used in `sendCoinsForPixels` functions to calculate the amount
/// COLs to transfer to pixel holders.
function setPixelConversionRate(uint256 _pixelConvRate) public pixelOrFounder {
pixelConvRate = _pixelConvRate;
}
/// @notice Get the conversion rate that was used in the most recent exchange of pixels to COLs.
function getPixelConversionRate() public view returns (uint256) {
return pixelConvRate;
}
/// @notice Distribute COL coins for pixels
/// COLs are spent from `pixelAccount` wallet. The amount of COLs is equal to `getPixelConversionRate() * pixels`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Amount of pixels to exchange into COLs
/// @param destination The wallet that holds the pixels.
function sendCoinsForPixels(
uint32 pixels, address destination
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
if (coins == 0) return;
require(coins <= accounts[pixelAccount]);
accounts[destination] = accounts[destination].add(coins);
accounts[pixelAccount] -= coins;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// This function consumes less gas compared to a batch transaction of `sendCoinsForPixels`.
/// `pixels[i]` specifies the amount of pixels belonging to `destinations[i]` wallet.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to i-th wallet is equal to `getPixelConversionRate() * pixels[i]`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Array of pixel amounts to exchange into COLs
/// @param destinations Array of addresses of wallets that hold pixels.
function sendCoinsForPixels_Batch(
uint32[] memory pixels,
address[] memory destinations
) public pixelOrFounder {
require(pixels.length == destinations.length);
uint256 total = 0;
for (uint256 i = 0; i < pixels.length; i++) {
uint256 coins = pixels[i]*pixelConvRate;
address dst = destinations[i];
accounts[dst] = accounts[dst].add(coins);
total += coins;
}
require(total <= accounts[pixelAccount]);
accounts[pixelAccount] -= total;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to each wallet is equal to `getPixelConversionRate() * pixels`
/// @dev The difference between `sendCoinsForPixels_Array` and `sendCoinsForPixels_Batch`
/// is that all destination wallets hold the same amount of pixels.
/// This optimization saves about 10% of gas compared to `sendCoinsForPixels_Batch`
/// with the same amount of recipients.
/// @param pixels Amount of pixels to exchange. All of `recipients` hold the same amount of pixels.
/// @param recipients Addresses of wallets, holding `pixels` amount of pixels.
function sendCoinsForPixels_Array(
uint32 pixels, address[] memory recipients
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
uint256 total = coins * recipients.length;
if (total == 0) return;
require(total <= accounts[pixelAccount]);
for (uint256 i; i < recipients.length; i++) {
address dst = recipients[i];
accounts[dst] = accounts[dst].add(coins);
}
accounts[pixelAccount] -= total;
}
}
/// @title Smart contract for Color Coin token.
/// @notice Color is the next generation platform for high-performance sophisticated decentralized applications (dApps). https://www.colors.org/
/// @dev Not intended for reuse.
contract ColorCoin is ColorCoinWithPixel {
/// @notice Token name
string public constant name = "Color Coin";
/// @notice Token symbol
string public constant symbol = "COL";
/// @notice Precision in fixed point arithmetics
uint8 public constant decimals = 18;
/// @notice Initialises a newly created instance
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinWithPixel (_totalSupply, _founder, _admin, _pixelCoinSupply, _pixelAccount)
{
}
} | Calls `selfdestruct` operator and transfers all Ethers to the founder (if any) | function destroy() public onlyAdmin {
selfdestruct(founder);
}
| 6,455,003 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
//Interface
import { ITokenERC20 } from "../interfaces/token/ITokenERC20.sol";
// Token
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
// Security
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
// Signature utils
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
// Meta transactions
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
// Utils
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
// Thirdweb top-level
import "../interfaces/ITWFee.sol";
contract TokenERC20 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
ERC20BurnableUpgradeable,
ERC20PausableUpgradeable,
ERC20VotesUpgradeable,
ITokenERC20,
AccessControlEnumerableUpgradeable
{
using ECDSAUpgradeable for bytes32;
bytes32 private constant MODULE_TYPE = bytes32("TokenERC20");
uint256 private constant VERSION = 1;
bytes32 private constant TYPEHASH =
keccak256(
"MintRequest(address to,address primarySaleRecipient,uint256 quantity,uint256 price,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)"
);
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 internal constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 internal constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev The thirdweb contract with fee related information.
ITWFee internal immutable thirdwebFee;
/// @dev Returns the URI for the storefront-level metadata of the contract.
string public contractURI;
/// @dev Max bps in the thirdweb system
uint128 internal constant MAX_BPS = 10_000;
/// @dev The % of primary sales collected by the contract as fees.
uint128 internal platformFeeBps;
/// @dev The adress that receives all primary sales value.
address internal platformFeeRecipient;
/// @dev The adress that receives all primary sales value.
address public primarySaleRecipient;
/// @dev Mapping from mint request UID => whether the mint request is processed.
mapping(bytes32 => bool) private minted;
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _primarySaleRecipient,
address _platformFeeRecipient,
uint256 _platformFeeBps
) external initializer {
__ERC2771Context_init_unchained(_trustedForwarders);
__ERC20Permit_init(_name);
__ERC20_init_unchained(_name, _symbol);
contractURI = _contractURI;
primarySaleRecipient = _primarySaleRecipient;
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint128(_platformFeeBps);
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(PAUSER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/// @dev Returns the module type of the contract.
function contractType() external pure virtual returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure virtual returns (uint8) {
return uint8(VERSION);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._afterTokenTransfer(from, to, amount);
}
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "transfers restricted.");
}
}
function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._burn(account, amount);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "not minter.");
_mintTo(to, amount);
}
/// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call).
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) {
address signer = recoverAddress(_req, _signature);
return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer);
}
/// @dev Mints tokens according to the provided mint request.
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant {
address signer = verifyRequest(_req, _signature);
address receiver = _req.to == address(0) ? _msgSender() : _req.to;
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
collectPrice(saleRecipient, _req.currency, _req.price);
_mintTo(receiver, _req.quantity);
emit TokensMintedWithSignature(signer, receiver, _req);
}
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "bps <= 10000.");
platformFeeBps = uint64(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectPrice(
address _primarySaleRecipient,
address _currency,
uint256 _price
) internal {
if (_price == 0) {
return;
}
uint256 platformFees = (_price * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (_price * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == _price, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
_primarySaleRecipient,
_price - platformFees - twFee
);
}
/// @dev Mints `amount` of tokens to `to`
function _mintTo(address _to, uint256 _amount) internal {
_mint(_to, _amount);
emit TokensMinted(_to, _amount);
}
/// @dev Verifies that a mint request is valid.
function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) {
(bool success, address signer) = verify(_req, _signature);
require(success, "invalid signature");
require(
_req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp,
"request expired"
);
minted[_req.uid] = true;
return signer;
}
/// @dev Returns the address of the signer of the mint request.
function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) {
return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature);
}
/// @dev Resolves 'stack too deep' error in `recoverAddress`.
function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) {
return
abi.encode(
TYPEHASH,
_req.to,
_req.primarySaleRecipient,
_req.quantity,
_req.price,
_req.currency,
_req.validityStartTimestamp,
_req.validityEndTimestamp,
_req.uid
);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_unpause();
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
interface ITokenERC20 is IThirdwebContract, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC20Upgradeable {
/**
* @notice The body of a request to mint tokens.
*
* @param to The receiver of the tokens to mint.
* @param primarySaleRecipient The receiver of the primary sale funds from the mint.
* @param quantity The quantity of tpkens to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
address primarySaleRecipient;
uint256 quantity;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 quantityMinted);
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(address indexed signer, address indexed mintedTo, MintRequest mintRequest);
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal onlyInitializing {
}
function __ERC20Burnable_init_unchained() internal onlyInitializing {
}
/**
* @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`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../governance/utils/IVotesUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable {
function __ERC20Votes_init() internal onlyInitializing {
}
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library CurrencyTransferLib {
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
require(success, "currency transfer failed.");
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20WithBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
uint256 balBefore = IERC20Upgradeable(_currency).balanceOf(_to);
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20Upgradeable(_currency).balanceOf(_to);
require(success && (balAfter == balBefore + _amount), "currency transfer failed.");
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
require(IERC20Upgradeable(_nativeTokenWrapper).transfer(to, value), "transfer failed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// 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 IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 Contracts guidelines: functions revert
* instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 this function is
* overridden;
*
* 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 override 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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotesUpgradeable {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
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 SafeCastUpgradeable {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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 {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
} | Verifies that a mint request is valid. | function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) {
(bool success, address signer) = verify(_req, _signature);
require(success, "invalid signature");
require(
_req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp,
"request expired"
);
minted[_req.uid] = true;
return signer;
}
| 409,470 |
/*
Zethr | https://zethr.io
(c) Copyright 2018 | All Rights Reserved
This smart contract was developed by the Zethr Dev Team and its source code remains property of the Zethr Project.
*/
pragma solidity ^0.4.24;
// File: contracts/Libraries/SafeMath.sol
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;
}
}
// File: contracts/Libraries/ZethrTierLibrary.sol
library ZethrTierLibrary {
uint constant internal magnitude = 2 ** 64;
// Gets the tier (1-7) of the divs sent based off of average dividend rate
// This is an index used to call into the correct sub-bankroll to withdraw tokens
function getTier(uint divRate) internal pure returns (uint8) {
// Divide the average dividned rate by magnitude
// Remainder doesn't matter because of the below logic
uint actualDiv = divRate / magnitude;
if (actualDiv >= 30) {
return 6;
} else if (actualDiv >= 25) {
return 5;
} else if (actualDiv >= 20) {
return 4;
} else if (actualDiv >= 15) {
return 3;
} else if (actualDiv >= 10) {
return 2;
} else if (actualDiv >= 5) {
return 1;
} else if (actualDiv >= 2) {
return 0;
} else {
// Impossible
revert();
}
}
function getDivRate(uint _tier)
internal pure
returns (uint8)
{
if (_tier == 0) {
return 2;
} else if (_tier == 1) {
return 5;
} else if (_tier == 2) {
return 10;
} else if (_tier == 3) {
return 15;
} else if (_tier == 4) {
return 20;
} else if (_tier == 5) {
return 25;
} else if (_tier == 6) {
return 33;
} else {
revert();
}
}
}
// File: contracts/ERC/ERC223Receiving.sol
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
// File: contracts/ZethrMultiSigWallet.sol
/* Zethr MultisigWallet
*
* Standard multisig wallet
* Holds the bankroll ETH, as well as the bankroll 33% ZTH tokens.
*/
contract ZethrMultiSigWallet is ERC223Receiving {
using SafeMath for uint;
/*=================================
= EVENTS =
=================================*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WhiteListAddition(address indexed contractAddress);
event WhiteListRemoval(address indexed contractAddress);
event RequirementChange(uint required);
event BankrollInvest(uint amountReceived);
/*=================================
= VARIABLES =
=================================*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
bool internal reEntered = false;
uint constant public MAX_OWNER_COUNT = 15;
/*=================================
= CUSTOM CONSTRUCTS =
=================================*/
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
struct TKN {
address sender;
uint value;
}
/*=================================
= MODIFIERS =
=================================*/
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (isOwner[caller])
_;
else
revert();
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
/*=================================
= PUBLIC FUNCTIONS =
=================================*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor (address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
// Add owners
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
// Set owners
owners = _owners;
// Set required
required = _required;
}
/** Testing only.
function exitAll()
public
{
uint tokenBalance = ZTHTKN.balanceOf(address(this));
ZTHTKN.sell(tokenBalance - 1e18);
ZTHTKN.sell(1e18);
ZTHTKN.withdraw(address(0x0));
}
**/
/// @dev Fallback function allows Ether to be deposited.
function()
public
payable
{
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
validRequirement(owners.length, required)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txToExecute = transactions[transactionId];
txToExecute.executed = true;
if (txToExecute.destination.call.value(txToExecute.value)(txToExecute.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txToExecute.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*=================================
= OPERATOR FUNCTIONS =
=================================*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/)
public
returns (bool)
{
return true;
}
}
// File: contracts/Bankroll/Interfaces/ZethrTokenBankrollInterface.sol
// Zethr token bankroll function prototypes
contract ZethrTokenBankrollInterface is ERC223Receiving {
uint public jackpotBalance;
function getMaxProfit(address) public view returns (uint);
function gameTokenResolution(uint _toWinnerAmount, address _winnerAddress, uint _toJackpotAmount, address _jackpotAddress, uint _originalBetSize) external;
function payJackpotToWinner(address _winnerAddress, uint payoutDivisor) public;
}
// File: contracts/Bankroll/Interfaces/ZethrBankrollControllerInterface.sol
contract ZethrBankrollControllerInterface is ERC223Receiving {
address public jackpotAddress;
ZethrTokenBankrollInterface[7] public tokenBankrolls;
ZethrMultiSigWallet public multiSigWallet;
mapping(address => bool) public validGameAddresses;
function gamePayoutResolver(address _resolver, uint _tokenAmount) public;
function isTokenBankroll(address _address) public view returns (bool);
function getTokenBankrollAddressFromTier(uint8 _tier) public view returns (address);
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
// File: contracts/ERC/ERC721Interface.sol
contract ERC721Interface {
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 Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
// File: contracts/Libraries/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* 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 addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint 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.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: contracts/Games/ZethrDividendCards.sol
contract ZethrDividendCards is ERC721Interface {
using SafeMath for uint;
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new dividend card comes into existence.
event Birth(uint tokenId, string name, address owner);
/// @dev The TokenSold event is fired whenever a token (dividend card, in this case) is sold.
event TokenSold(uint tokenId, uint oldPrice, uint newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in current draft of ERC721.
/// Ownership is assigned, including births.
event Transfer(address from, address to, uint tokenId);
// Events for calculating card profits / errors
event BankrollDivCardProfit(uint bankrollProfit, uint percentIncrease, address oldOwner);
event BankrollProfitFailure(uint bankrollProfit, uint percentIncrease, address oldOwner);
event UserDivCardProfit(uint divCardProfit, uint percentIncrease, address oldOwner);
event DivCardProfitFailure(uint divCardProfit, uint percentIncrease, address oldOwner);
event masterCardProfit(uint toMaster, address _masterAddress, uint _divCardId);
event masterCardProfitFailure(uint toMaster, address _masterAddress, uint _divCardId);
event regularCardProfit(uint toRegular, address _regularAddress, uint _divCardId);
event regularCardProfitFailure(uint toRegular, address _regularAddress, uint _divCardId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "ZethrDividendCard";
string public constant SYMBOL = "ZDC";
address public BANKROLL;
/*** STORAGE ***/
/// @dev A mapping from dividend card indices to the address that owns them.
/// All dividend cards have a valid owner address.
mapping (uint => address) public divCardIndexToOwner;
// A mapping from a dividend rate to the card index.
mapping (uint => uint) public divCardRateToIndex;
// @dev A mapping from owner address to the number of dividend cards that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint) private ownershipDivCardCount;
/// @dev A mapping from dividend card indices to an address that has been approved to call
/// transferFrom(). Each dividend card can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint => address) public divCardIndexToApproved;
// @dev A mapping from dividend card indices to the price of the dividend card.
mapping (uint => uint) private divCardIndexToPrice;
mapping (address => bool) internal administrators;
address public creator;
bool public onSale;
/*** DATATYPES ***/
struct Card {
string name;
uint percentIncrease;
}
Card[] private divCards;
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
constructor (address _bankroll) public {
creator = msg.sender;
BANKROLL = _bankroll;
createDivCard("2%", 1 ether, 2);
divCardRateToIndex[2] = 0;
createDivCard("5%", 1 ether, 5);
divCardRateToIndex[5] = 1;
createDivCard("10%", 1 ether, 10);
divCardRateToIndex[10] = 2;
createDivCard("15%", 1 ether, 15);
divCardRateToIndex[15] = 3;
createDivCard("20%", 1 ether, 20);
divCardRateToIndex[20] = 4;
createDivCard("25%", 1 ether, 25);
divCardRateToIndex[25] = 5;
createDivCard("33%", 1 ether, 33);
divCardRateToIndex[33] = 6;
createDivCard("MASTER", 5 ether, 10);
divCardRateToIndex[999] = 7;
onSale = true;
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true; // Norsefire
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true; // klob
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true; // Etherguy
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true; // blurr
administrators[msg.sender] = true; // Helps with debugging
}
/*** MODIFIERS ***/
// Modifier to prevent contracts from interacting with the flip cards
modifier isNotContract()
{
require (msg.sender == tx.origin);
_;
}
// Modifier to prevent purchases before we open them up to everyone
modifier hasStarted()
{
require (onSale == true);
_;
}
modifier isAdmin()
{
require(administrators[msg.sender]);
_;
}
/*** PUBLIC FUNCTIONS ***/
// Administrative update of the bankroll contract address
function setBankroll(address where)
public
isAdmin
{
BANKROLL = where;
}
/// @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
isNotContract
{
// Caller must own token.
require(_owns(msg.sender, _tokenId));
divCardIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/// 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 ownershipDivCardCount[_owner];
}
// Creates a div card with bankroll as the owner
function createDivCard(string _name, uint _price, uint _percentIncrease)
public
onlyCreator
{
_createDivCard(_name, BANKROLL, _price, _percentIncrease);
}
// Opens the dividend cards up for sale.
function startCardSale()
public
isAdmin
{
onSale = true;
}
/// @notice Returns all the relevant information about a specific div card
/// @param _divCardId The tokenId of the div card of interest.
function getDivCard(uint _divCardId)
public
view
returns (string divCardName, uint sellingPrice, address owner)
{
Card storage divCard = divCards[_divCardId];
divCardName = divCard.name;
sellingPrice = divCardIndexToPrice[_divCardId];
owner = divCardIndexToOwner[_divCardId];
}
function implementsERC721()
public
pure
returns (bool)
{
return true;
}
/// @dev Required for ERC-721 compliance.
function name()
public
pure
returns (string)
{
return NAME;
}
/// For querying owner of token
/// @param _divCardId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _divCardId)
public
view
returns (address owner)
{
owner = divCardIndexToOwner[_divCardId];
require(owner != address(0));
return owner;
}
// Allows someone to send Ether and obtain a card
function purchase(uint _divCardId)
public
payable
hasStarted
isNotContract
{
address oldOwner = divCardIndexToOwner[_divCardId];
address newOwner = msg.sender;
// Get the current price of the card
uint currentPrice = divCardIndexToPrice[_divCardId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= currentPrice);
// To find the total profit, we need to know the previous price
// currentPrice = previousPrice * (100 + percentIncrease);
// previousPrice = currentPrice / (100 + percentIncrease);
uint percentIncrease = divCards[_divCardId].percentIncrease;
uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
// Calculate total profit and allocate 50% to old owner, 50% to bankroll
uint totalProfit = SafeMath.sub(currentPrice, previousPrice);
uint oldOwnerProfit = SafeMath.div(totalProfit, 2);
uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit);
oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
// Refund the sender the excess he sent
uint purchaseExcess = SafeMath.sub(msg.value, currentPrice);
// Raise the price by the percentage specified by the card
divCardIndexToPrice[_divCardId] = SafeMath.div(SafeMath.mul(currentPrice, (100 + percentIncrease)), 100);
// Transfer ownership
_transfer(oldOwner, newOwner, _divCardId);
// Using send rather than transfer to prevent contract exploitability.
if(BANKROLL.send(bankrollProfit)) {
emit BankrollDivCardProfit(bankrollProfit, percentIncrease, oldOwner);
} else {
emit BankrollProfitFailure(bankrollProfit, percentIncrease, oldOwner);
}
if(oldOwner.send(oldOwnerProfit)) {
emit UserDivCardProfit(oldOwnerProfit, percentIncrease, oldOwner);
} else {
emit DivCardProfitFailure(oldOwnerProfit, percentIncrease, oldOwner);
}
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _divCardId)
public
view
returns (uint price)
{
return divCardIndexToPrice[_divCardId];
}
function setCreator(address _creator)
public
onlyCreator
{
require(_creator != address(0));
creator = _creator;
}
/// @dev Required for ERC-721 compliance.
function symbol()
public
pure
returns (string)
{
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a dividend card.
/// @param _divCardId The ID of the card that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint _divCardId)
public
isNotContract
{
address newOwner = msg.sender;
address oldOwner = divCardIndexToOwner[_divCardId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _divCardId));
_transfer(oldOwner, newOwner, _divCardId);
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply()
public
view
returns (uint total)
{
return divCards.length;
}
/// Owner initates the transfer of the card to another account
/// @param _to The address for the card to be transferred to.
/// @param _divCardId The ID of the card that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint _divCardId)
public
isNotContract
{
require(_owns(msg.sender, _divCardId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _divCardId);
}
/// Third-party initiates transfer of a card from address _from to address _to
/// @param _from The address for the card to be transferred from.
/// @param _to The address for the card to be transferred to.
/// @param _divCardId The ID of the card that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint _divCardId)
public
isNotContract
{
require(_owns(_from, _divCardId));
require(_approved(_to, _divCardId));
require(_addressNotNull(_to));
_transfer(_from, _to, _divCardId);
}
function receiveDividends(uint _divCardRate)
public
payable
{
uint _divCardId = divCardRateToIndex[_divCardRate];
address _regularAddress = divCardIndexToOwner[_divCardId];
address _masterAddress = divCardIndexToOwner[7];
uint toMaster = msg.value.div(2);
uint toRegular = msg.value.sub(toMaster);
if(_masterAddress.send(toMaster)){
emit masterCardProfit(toMaster, _masterAddress, _divCardId);
} else {
emit masterCardProfitFailure(toMaster, _masterAddress, _divCardId);
}
if(_regularAddress.send(toRegular)) {
emit regularCardProfit(toRegular, _regularAddress, _divCardId);
} else {
emit regularCardProfitFailure(toRegular, _regularAddress, _divCardId);
}
}
/*** PRIVATE FUNCTIONS ***/
/// 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 checking approval of transfer for address _to
function _approved(address _to, uint _divCardId)
private
view
returns (bool)
{
return divCardIndexToApproved[_divCardId] == _to;
}
/// For creating a dividend card
function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease)
private
{
Card memory _divcard = Card({
name: _name,
percentIncrease: _percentIncrease
});
uint newCardId = divCards.push(_divcard) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newCardId == uint(uint32(newCardId)));
emit Birth(newCardId, _name, _owner);
divCardIndexToPrice[newCardId] = _price;
// This will assign ownership, and also emit the Transfer event as per ERC721 draft
_transfer(BANKROLL, _owner, newCardId);
}
/// Check for token ownership
function _owns(address claimant, uint _divCardId)
private
view
returns (bool)
{
return claimant == divCardIndexToOwner[_divCardId];
}
/// @dev Assigns ownership of a specific Card to an address.
function _transfer(address _from, address _to, uint _divCardId)
private
{
// Since the number of cards is capped to 2^32 we can't overflow this
ownershipDivCardCount[_to]++;
//transfer ownership
divCardIndexToOwner[_divCardId] = _to;
// When creating new div cards _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipDivCardCount[_from]--;
// clear any previously approved ownership exchange
delete divCardIndexToApproved[_divCardId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _divCardId);
}
}
// File: contracts/Zethr.sol
contract Zethr {
using SafeMath for uint;
/*=================================
= MODIFIERS =
=================================*/
modifier onlyHolders() {
require(myFrontEndTokens() > 0);
_;
}
modifier dividendHolder() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint incomingEthereum,
uint tokensMinted,
address indexed referredBy
);
event UserDividendRate(
address user,
uint divRate
);
event onTokenSell(
address indexed customerAddress,
uint tokensBurned,
uint ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint ethereumReinvested,
uint tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint tokens
);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint tokens
);
event Allocation(
uint toBankRoll,
uint toReferrer,
uint toTokenHolders,
uint toDivCardHolders,
uint forTokens
);
event Referral(
address referrer,
uint amountReceived
);
/*=====================================
= CONSTANTS =
=====================================*/
uint8 constant public decimals = 18;
uint constant internal tokenPriceInitial_ = 0.000653 ether;
uint constant internal magnitude = 2 ** 64;
uint constant internal icoHardCap = 250 ether;
uint constant internal addressICOLimit = 1 ether;
uint constant internal icoMinBuyIn = 0.1 finney;
uint constant internal icoMaxGasPrice = 50000000000 wei;
uint constant internal MULTIPLIER = 9615;
uint constant internal MIN_ETH_BUYIN = 0.0001 ether;
uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether;
uint constant internal MIN_TOKEN_TRANSFER = 1e10;
uint constant internal referrer_percentage = 25;
uint public stakingRequirement = 100e18;
/*================================
= CONFIGURABLES =
================================*/
string public name = "Zethr";
string public symbol = "ZTH";
//bytes32 constant public icoHashedPass = bytes32(0x5ddcde33b94b19bdef79dd9ea75be591942b9ec78286d64b44a356280fb6a262); // public
bytes32 constant public icoHashedPass = bytes32(0x8a6ddee3fb2508ff4a5b02b48e9bc4566d0f3e11f306b0f75341bf235662a9e3); // test hunter2
address internal bankrollAddress;
ZethrDividendCards divCardContract;
/*================================
= DATASETS =
================================*/
// Tracks front & backend tokens
mapping(address => uint) internal frontTokenBalanceLedger_;
mapping(address => uint) internal dividendTokenBalanceLedger_;
mapping(address =>
mapping(address => uint))
public allowed;
// Tracks dividend rates for users
mapping(uint8 => bool) internal validDividendRates_;
mapping(address => bool) internal userSelectedRate;
mapping(address => uint8) internal userDividendRate;
// Payout tracking
mapping(address => uint) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
// ICO per-address limit tracking
mapping(address => uint) internal ICOBuyIn;
uint public tokensMintedDuringICO;
uint public ethInvestedDuringICO;
uint public currentEthInvested;
uint internal tokenSupply = 0;
uint internal divTokenSupply = 0;
uint internal profitPerDivToken;
mapping(address => bool) public administrators;
bool public icoPhase = false;
bool public regularPhase = false;
uint icoOpenTime;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
constructor (address _bankrollAddress, address _divCardAddress)
public
{
bankrollAddress = _bankrollAddress;
divCardContract = ZethrDividendCards(_divCardAddress);
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
// Norsefire
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
// klob
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
// Etherguy
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
// blurr
administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true;
// oguzhanox
administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true;
// Randall
administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true;
// TropicalRogue
administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true;
// cryptodude
administrators[msg.sender] = true;
// Helps with debugging!
validDividendRates_[2] = true;
validDividendRates_[5] = true;
validDividendRates_[10] = true;
validDividendRates_[15] = true;
validDividendRates_[20] = true;
validDividendRates_[25] = true;
validDividendRates_[33] = true;
userSelectedRate[bankrollAddress] = true;
userDividendRate[bankrollAddress] = 33;
}
/**
* Same as buy, but explicitly sets your dividend percentage.
* If this has been called before, it will update your `default' dividend
* percentage for regular buy transactions going forward.
*/
function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string /*providedUnhashedPass*/)
public
payable
returns (uint)
{
require(icoPhase || regularPhase);
if (icoPhase) {
// Anti-bot measures - not perfect, but should help some.
// bytes32 hashedProvidedPass = keccak256(providedUnhashedPass);
//require(hashedProvidedPass == icoHashedPass || msg.sender == bankrollAddress); // test; remove
uint gasPrice = tx.gasprice;
// Prevents ICO buyers from getting substantially burned if the ICO is reached
// before their transaction is processed.
require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap);
}
// Dividend percentage should be a currently accepted value.
require(validDividendRates_[_divChoice]);
// Set the dividend fee percentage denominator.
userSelectedRate[msg.sender] = true;
userDividendRate[msg.sender] = _divChoice;
emit UserDividendRate(msg.sender, _divChoice);
// Finally, purchase tokens.
purchaseTokens(msg.value, _referredBy);
}
// All buys except for the above one require regular phase.
function buy(address _referredBy)
public
payable
returns (uint)
{
require(regularPhase);
address _customerAddress = msg.sender;
require(userSelectedRate[_customerAddress]);
purchaseTokens(msg.value, _referredBy);
}
function buyAndTransfer(address _referredBy, address target)
public
payable
{
bytes memory empty;
buyAndTransfer(_referredBy, target, empty, 20);
}
function buyAndTransfer(address _referredBy, address target, bytes _data)
public
payable
{
buyAndTransfer(_referredBy, target, _data, 20);
}
// Overload
function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice)
public
payable
{
require(regularPhase);
address _customerAddress = msg.sender;
uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender];
if (userSelectedRate[_customerAddress] && divChoice == 0) {
purchaseTokens(msg.value, _referredBy);
} else {
buyAndSetDivPercentage(_referredBy, divChoice, "0x0");
}
uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance);
transferTo(msg.sender, target, difference, _data);
}
// Fallback function only works during regular phase - part of anti-bot protection.
function()
payable
public
{
/**
/ If the user has previously set a dividend rate, sending
/ Ether directly to the contract simply purchases more at
/ the most recent rate. If this is their first time, they
/ are automatically placed into the 20% rate `bucket'.
**/
require(regularPhase);
address _customerAddress = msg.sender;
if (userSelectedRate[_customerAddress]) {
purchaseTokens(msg.value, 0x0);
} else {
buyAndSetDivPercentage(0x0, 20, "0x0");
}
}
function reinvest()
dividendHolder()
public
{
require(regularPhase);
uint _dividends = myDividends(false);
// Pay out requisite `virtual' dividends.
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint _tokens = purchaseTokens(_dividends, 0x0);
// Fire logging event.
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
require(regularPhase);
// Retrieve token balance for caller, then sell them all.
address _customerAddress = msg.sender;
uint _tokens = frontTokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw(_customerAddress);
}
function withdraw(address _recipient)
dividendHolder()
public
{
require(regularPhase);
// Setup data
address _customerAddress = msg.sender;
uint _dividends = myDividends(false);
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
if (_recipient == address(0x0)) {
_recipient = msg.sender;
}
_recipient.transfer(_dividends);
// Fire logging event.
emit onWithdraw(_recipient, _dividends);
}
// Sells front-end tokens.
// Logic concerning step-pricing of tokens pre/post-ICO is encapsulated in tokensToEthereum_.
function sell(uint _amountOfTokens)
onlyHolders()
public
{
// No selling during the ICO. You don't get to flip that fast, sorry!
require(!icoPhase);
require(regularPhase);
require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
uint _frontEndTokensToBurn = _amountOfTokens;
// Calculate how many dividend tokens this action burns.
// Computed as the caller's average dividend rate multiplied by the number of front-end tokens held.
// As an additional guard, we ensure that the dividend rate is between 2 and 50 inclusive.
uint userDivRate = getUserAverageDividendRate(msg.sender);
require((2 * magnitude) <= userDivRate && (50 * magnitude) >= userDivRate);
uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude);
// Calculate ethereum received before dividends
uint _ethereum = tokensToEthereum_(_frontEndTokensToBurn);
if (_ethereum > currentEthInvested) {
// Well, congratulations, you've emptied the coffers.
currentEthInvested = 0;
} else {currentEthInvested = currentEthInvested - _ethereum;}
// Calculate dividends generated from the sale.
uint _dividends = (_ethereum.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude);
// Calculate Ethereum receivable net of dividends.
uint _taxedEthereum = _ethereum.sub(_dividends);
// Burn the sold tokens (both front-end and back-end variants).
tokenSupply = tokenSupply.sub(_frontEndTokensToBurn);
divTokenSupply = divTokenSupply.sub(_divTokensToBurn);
// Subtract the token balances for the seller
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn);
// Update dividends tracker
int256 _updatedPayouts = (int256) (profitPerDivToken * _divTokensToBurn + (_taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
// Let's avoid breaking arithmetic where we can, eh?
if (divTokenSupply > 0) {
// Update the value of each remaining back-end dividend token.
profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply);
}
// Fire logging event.
emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* No charge incurred for the transfer. We'd make a terrible bank.
*/
function transfer(address _toAddress, uint _amountOfTokens)
onlyHolders()
public
returns (bool)
{
require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
bytes memory empty;
transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty);
return true;
}
function approve(address spender, uint tokens)
public
returns (bool)
{
address _customerAddress = msg.sender;
allowed[_customerAddress][spender] = tokens;
// Fire logging event.
emit Approval(_customerAddress, spender, tokens);
// Good old ERC20.
return true;
}
/**
* Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition.
* No charge incurred for the transfer. No seriously, we'd make a terrible bank.
*/
function transferFrom(address _from, address _toAddress, uint _amountOfTokens)
public
returns (bool)
{
// Setup variables
address _customerAddress = _from;
bytes memory empty;
// Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens,
// and are transferring at least one full token.
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress]
&& _amountOfTokens <= allowed[_customerAddress][msg.sender]);
transferFromInternal(_from, _toAddress, _amountOfTokens, empty);
// Good old ERC20.
return true;
}
function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data)
public
{
if (_from != msg.sender) {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]
&& _amountOfTokens <= allowed[_from][msg.sender]);
}
else {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]);
}
transferFromInternal(_from, _to, _amountOfTokens, _data);
}
// Who'd have thought we'd need this thing floating around?
function totalSupply()
public
view
returns (uint256)
{
return tokenSupply;
}
// Anyone can start the regular phase 2 weeks after the ICO phase starts.
// In case the devs die. Or something.
function publicStartRegularPhase()
public
{
require(now > (icoOpenTime + 2 weeks) && icoOpenTime != 0);
icoPhase = false;
regularPhase = true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
// Fire the starting gun and then duck for cover.
function startICOPhase()
onlyAdministrator()
public
{
// Prevent us from startaring the ICO phase again
require(icoOpenTime == 0);
icoPhase = true;
icoOpenTime = now;
}
// Fire the ... ending gun?
function endICOPhase()
onlyAdministrator()
public
{
icoPhase = false;
}
function startRegularPhase()
onlyAdministrator
public
{
// disable ico phase in case if that was not disabled yet
icoPhase = false;
regularPhase = true;
}
// The death of a great man demands the birth of a great son.
function setAdministrator(address _newAdmin, bool _status)
onlyAdministrator()
public
{
administrators[_newAdmin] = _status;
}
function setStakingRequirement(uint _amountOfTokens)
onlyAdministrator()
public
{
// This plane only goes one way, lads. Never below the initial.
require(_amountOfTokens >= 100e18);
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function changeBankroll(address _newBankrollAddress)
onlyAdministrator
public
{
bankrollAddress = _newBankrollAddress;
}
/*---------- HELPERS AND CALCULATORS ----------*/
function totalEthereumBalance()
public
view
returns (uint)
{
return address(this).balance;
}
function totalEthereumICOReceived()
public
view
returns (uint)
{
return ethInvestedDuringICO;
}
/**
* Retrieves your currently selected dividend rate.
*/
function getMyDividendRate()
public
view
returns (uint8)
{
address _customerAddress = msg.sender;
require(userSelectedRate[_customerAddress]);
return userDividendRate[_customerAddress];
}
/**
* Retrieve the total frontend token supply
*/
function getFrontEndTokenSupply()
public
view
returns (uint)
{
return tokenSupply;
}
/**
* Retreive the total dividend token supply
*/
function getDividendTokenSupply()
public
view
returns (uint)
{
return divTokenSupply;
}
/**
* Retrieve the frontend tokens owned by the caller
*/
function myFrontEndTokens()
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return getFrontEndTokenBalanceOf(_customerAddress);
}
/**
* Retrieve the dividend tokens owned by the caller
*/
function myDividendTokens()
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return getDividendTokenBalanceOf(_customerAddress);
}
function myReferralDividends()
public
view
returns (uint)
{
return myDividends(true) - myDividends(false);
}
function myDividends(bool _includeReferralBonus)
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function theDividendsOf(bool _includeReferralBonus, address _customerAddress)
public
view
returns (uint)
{
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function getFrontEndTokenBalanceOf(address _customerAddress)
view
public
returns (uint)
{
return frontTokenBalanceLedger_[_customerAddress];
}
function balanceOf(address _owner)
view
public
returns (uint)
{
return getFrontEndTokenBalanceOf(_owner);
}
function getDividendTokenBalanceOf(address _customerAddress)
view
public
returns (uint)
{
return dividendTokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns (uint)
{
return (uint) ((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
// Get the sell price at the user's average dividend rate
function sellPrice()
public
view
returns (uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate the price.
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
// Factor in the user's average dividend rate
uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude));
return theSellPrice;
}
// Get the buy price at a particular dividend rate
function buyPrice(uint dividendRate)
public
view
returns (uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate the price.
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
// Factor in the user's selected dividend rate
uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price);
return theBuyPrice;
}
function calculateTokensReceived(uint _ethereumToSpend)
public
view
returns (uint)
{
uint _dividends = (_ethereumToSpend.mul(userDividendRate[msg.sender])).div(100);
uint _taxedEthereum = _ethereumToSpend.sub(_dividends);
uint _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
// When selling tokens, we need to calculate the user's current dividend rate.
// This is different from their selected dividend rate.
function calculateEthereumReceived(uint _tokensToSell)
public
view
returns (uint)
{
require(_tokensToSell <= tokenSupply);
uint _ethereum = tokensToEthereum_(_tokensToSell);
uint userAverageDividendRate = getUserAverageDividendRate(msg.sender);
uint _dividends = (_ethereum.mul(userAverageDividendRate).div(100)).div(magnitude);
uint _taxedEthereum = _ethereum.sub(_dividends);
return _taxedEthereum;
}
/*
* Get's a user's average dividend rate - which is just their divTokenBalance / tokenBalance
* We multiply by magnitude to avoid precision errors.
*/
function getUserAverageDividendRate(address user) public view returns (uint) {
return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]);
}
function getMyAverageDividendRate() public view returns (uint) {
return getUserAverageDividendRate(msg.sender);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/* Purchase tokens with Ether.
During ICO phase, dividends should go to the bankroll
During normal operation:
0.5% should go to the master dividend card
0.5% should go to the matching dividend card
25% of dividends should go to the referrer, if any is provided. */
function purchaseTokens(uint _incomingEthereum, address _referredBy)
internal
returns (uint)
{
require(_incomingEthereum >= MIN_ETH_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min eth buyin threshold.");
uint toBankRoll;
uint toReferrer;
uint toTokenHolders;
uint toDivCardHolders;
uint dividendAmount;
uint tokensBought;
uint dividendTokensBought;
uint remainingEth = _incomingEthereum;
uint fee;
// 1% for dividend card holders is taken off before anything else
if (regularPhase) {
toDivCardHolders = _incomingEthereum.div(100);
remainingEth = remainingEth.sub(toDivCardHolders);
}
/* Next, we tax for dividends:
Dividends = (ethereum * div%) / 100
Important note: if we're out of the ICO phase, the 1% sent to div-card holders
is handled prior to any dividend taxes are considered. */
// Grab the user's dividend rate
uint dividendRate = userDividendRate[msg.sender];
// Calculate the total dividends on this buy
dividendAmount = (remainingEth.mul(dividendRate)).div(100);
remainingEth = remainingEth.sub(dividendAmount);
// If we're in the ICO and bankroll is buying, don't tax
if (icoPhase && msg.sender == bankrollAddress) {
remainingEth = remainingEth + dividendAmount;
}
// Calculate how many tokens to buy:
tokensBought = ethereumToTokens_(remainingEth);
dividendTokensBought = tokensBought.mul(dividendRate);
// This is where we actually mint tokens:
tokenSupply = tokenSupply.add(tokensBought);
divTokenSupply = divTokenSupply.add(dividendTokensBought);
/* Update the total investment tracker
Note that this must be done AFTER we calculate how many tokens are bought -
because ethereumToTokens needs to know the amount *before* investment, not *after* investment. */
currentEthInvested = currentEthInvested + remainingEth;
// If ICO phase, all the dividends go to the bankroll
if (icoPhase) {
toBankRoll = dividendAmount;
// If the bankroll is buying, we don't want to send eth back to the bankroll
// Instead, let's just give it the tokens it would get in an infinite recursive buy
if (msg.sender == bankrollAddress) {
toBankRoll = 0;
}
toReferrer = 0;
toTokenHolders = 0;
/* ethInvestedDuringICO tracks how much Ether goes straight to tokens,
not how much Ether we get total.
this is so that our calculation using "investment" is accurate. */
ethInvestedDuringICO = ethInvestedDuringICO + remainingEth;
tokensMintedDuringICO = tokensMintedDuringICO + tokensBought;
// Cannot purchase more than the hard cap during ICO.
require(ethInvestedDuringICO <= icoHardCap);
// Contracts aren't allowed to participate in the ICO.
require(tx.origin == msg.sender || msg.sender == bankrollAddress);
// Cannot purchase more then the limit per address during the ICO.
ICOBuyIn[msg.sender] += remainingEth;
//require(ICOBuyIn[msg.sender] <= addressICOLimit || msg.sender == bankrollAddress); // test:remove
// Stop the ICO phase if we reach the hard cap
if (ethInvestedDuringICO == icoHardCap) {
icoPhase = false;
}
} else {
// Not ICO phase, check for referrals
// 25% goes to referrers, if set
// toReferrer = (dividends * 25)/100
if (_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
frontTokenBalanceLedger_[_referredBy] >= stakingRequirement)
{
toReferrer = (dividendAmount.mul(referrer_percentage)).div(100);
referralBalance_[_referredBy] += toReferrer;
emit Referral(_referredBy, toReferrer);
}
// The rest of the dividends go to token holders
toTokenHolders = dividendAmount.sub(toReferrer);
fee = toTokenHolders * magnitude;
fee = fee - (fee - (dividendTokensBought * (toTokenHolders * magnitude / (divTokenSupply))));
// Finally, increase the divToken value
profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply));
payoutsTo_[msg.sender] += (int256) ((profitPerDivToken * dividendTokensBought) - fee);
}
// Update the buyer's token amounts
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(dividendTokensBought);
// Transfer to bankroll and div cards
if (toBankRoll != 0) {ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)();}
if (regularPhase) {divCardContract.receiveDividends.value(toDivCardHolders)(dividendRate);}
// This event should help us track where all the eth is going
emit Allocation(toBankRoll, toReferrer, toTokenHolders, toDivCardHolders, remainingEth);
// Sanity checking
uint sum = toBankRoll + toReferrer + toTokenHolders + toDivCardHolders + remainingEth - _incomingEthereum;
assert(sum == 0);
}
// How many tokens one gets from a certain amount of ethereum.
function ethereumToTokens_(uint _ethereumAmount)
public
view
returns (uint)
{
require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth.");
if (icoPhase) {
return _ethereumAmount.div(tokenPriceInitial_) * 1e18;
}
/*
* i = investment, p = price, t = number of tokens
*
* i_current = p_initial * t_current (for t_current <= t_initial)
* i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial)
*
* t_current = i_current / p_initial (for i_current <= i_initial)
* t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial)
*/
// First, separate out the buy into two segments:
// 1) the amount of eth going towards ico-price tokens
// 2) the amount of eth going towards pyramid-price (variable) tokens
uint ethTowardsICOPriceTokens = 0;
uint ethTowardsVariablePriceTokens = 0;
if (currentEthInvested >= ethInvestedDuringICO) {
// Option One: All the ETH goes towards variable-price tokens
ethTowardsVariablePriceTokens = _ethereumAmount;
} else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount <= ethInvestedDuringICO) {
// Option Two: All the ETH goes towards ICO-price tokens
ethTowardsICOPriceTokens = _ethereumAmount;
} else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount > ethInvestedDuringICO) {
// Option Three: Some ETH goes towards ICO-price tokens, some goes towards variable-price tokens
ethTowardsICOPriceTokens = ethInvestedDuringICO.sub(currentEthInvested);
ethTowardsVariablePriceTokens = _ethereumAmount.sub(ethTowardsICOPriceTokens);
} else {
// Option Four: Should be impossible, and compiler should optimize it out of existence.
revert();
}
// Sanity check:
assert(ethTowardsICOPriceTokens + ethTowardsVariablePriceTokens == _ethereumAmount);
// Separate out the number of tokens of each type this will buy:
uint icoPriceTokens = 0;
uint varPriceTokens = 0;
// Now calculate each one per the above formulas.
// Note: since tokens have 18 decimals of precision we multiply the result by 1e18.
if (ethTowardsICOPriceTokens != 0) {
icoPriceTokens = ethTowardsICOPriceTokens.mul(1e18).div(tokenPriceInitial_);
}
if (ethTowardsVariablePriceTokens != 0) {
// Note: we can't use "currentEthInvested" for this calculation, we must use:
// currentEthInvested + ethTowardsICOPriceTokens
// This is because a split-buy essentially needs to simulate two separate buys -
// including the currentEthInvested update that comes BEFORE variable price tokens are bought!
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
/* We have the equations for total tokens above; note that this is for TOTAL.
To get the number of tokens this purchase buys, use the simulatedEthInvestedBefore
and the simulatedEthInvestedAfter and calculate the difference in tokens.
This is how many we get. */
uint tokensBefore = toPowerOfTwoThirds(simulatedEthBeforeInvested.mul(3).div(2)).mul(MULTIPLIER);
uint tokensAfter = toPowerOfTwoThirds(simulatedEthAfterInvested.mul(3).div(2)).mul(MULTIPLIER);
/* Note that we could use tokensBefore = tokenSupply + icoPriceTokens instead of dynamically calculating tokensBefore;
either should work.
Investment IS already multiplied by 1e18; however, because this is taken to a power of (2/3),
we need to multiply the result by 1e6 to get back to the correct number of decimals. */
varPriceTokens = (1e6) * tokensAfter.sub(tokensBefore);
}
uint totalTokensReceived = icoPriceTokens + varPriceTokens;
assert(totalTokensReceived > 0);
return totalTokensReceived;
}
// How much Ether we get from selling N tokens
function tokensToEthereum_(uint _tokens)
public
view
returns (uint)
{
require(_tokens >= MIN_TOKEN_SELL_AMOUNT, "Tried to sell too few tokens.");
/*
* i = investment, p = price, t = number of tokens
*
* i_current = p_initial * t_current (for t_current <= t_initial)
* i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial)
*
* t_current = i_current / p_initial (for i_current <= i_initial)
* t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial)
*/
// First, separate out the sell into two segments:
// 1) the amount of tokens selling at the ICO price.
// 2) the amount of tokens selling at the variable (pyramid) price
uint tokensToSellAtICOPrice = 0;
uint tokensToSellAtVariablePrice = 0;
if (tokenSupply <= tokensMintedDuringICO) {
// Option One: All the tokens sell at the ICO price.
tokensToSellAtICOPrice = _tokens;
} else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens >= tokensMintedDuringICO) {
// Option Two: All the tokens sell at the variable price.
tokensToSellAtVariablePrice = _tokens;
} else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens < tokensMintedDuringICO) {
// Option Three: Some tokens sell at the ICO price, and some sell at the variable price.
tokensToSellAtVariablePrice = tokenSupply.sub(tokensMintedDuringICO);
tokensToSellAtICOPrice = _tokens.sub(tokensToSellAtVariablePrice);
} else {
// Option Four: Should be impossible, and the compiler should optimize it out of existence.
revert();
}
// Sanity check:
assert(tokensToSellAtVariablePrice + tokensToSellAtICOPrice == _tokens);
// Track how much Ether we get from selling at each price function:
uint ethFromICOPriceTokens;
uint ethFromVarPriceTokens;
// Now, actually calculate:
if (tokensToSellAtICOPrice != 0) {
/* Here, unlike the sister equation in ethereumToTokens, we DON'T need to multiply by 1e18, since
we will be passed in an amount of tokens to sell that's already at the 18-decimal precision.
We need to divide by 1e18 or we'll have too much Ether. */
ethFromICOPriceTokens = tokensToSellAtICOPrice.mul(tokenPriceInitial_).div(1e18);
}
if (tokensToSellAtVariablePrice != 0) {
/* Note: Unlike the sister function in ethereumToTokens, we don't have to calculate any "virtual" token count.
This is because in sells, we sell the variable price tokens **first**, and then we sell the ICO-price tokens.
Thus there isn't any weird stuff going on with the token supply.
We have the equations for total investment above; note that this is for TOTAL.
To get the eth received from this sell, we calculate the new total investment after this sell.
Note that we divide by 1e6 here as the inverse of multiplying by 1e6 in ethereumToTokens. */
uint investmentBefore = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3);
uint investmentAfter = toPowerOfThreeHalves((tokenSupply - tokensToSellAtVariablePrice).div(MULTIPLIER * 1e6)).mul(2).div(3);
ethFromVarPriceTokens = investmentBefore.sub(investmentAfter);
}
uint totalEthReceived = ethFromVarPriceTokens + ethFromICOPriceTokens;
assert(totalEthReceived > 0);
return totalEthReceived;
}
function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data)
internal
{
require(regularPhase);
require(_toAddress != address(0x0));
address _customerAddress = _from;
uint _amountOfFrontEndTokens = _amountOfTokens;
// Withdraw all outstanding dividends first (including those generated from referrals).
if (theDividendsOf(true, _customerAddress) > 0) withdrawFrom(_customerAddress);
// Calculate how many back-end dividend tokens to transfer.
// This amount is proportional to the caller's average dividend rate multiplied by the proportion of tokens being transferred.
uint _amountOfDivTokens = _amountOfFrontEndTokens.mul(getUserAverageDividendRate(_customerAddress)).div(magnitude);
if (_customerAddress != msg.sender) {
// Update the allowed balance.
// Don't update this if we are transferring our own tokens (via transfer or buyAndTransfer)
allowed[_customerAddress][msg.sender] -= _amountOfTokens;
}
// Exchange tokens
frontTokenBalanceLedger_[_customerAddress] = frontTokenBalanceLedger_[_customerAddress].sub(_amountOfFrontEndTokens);
frontTokenBalanceLedger_[_toAddress] = frontTokenBalanceLedger_[_toAddress].add(_amountOfFrontEndTokens);
dividendTokenBalanceLedger_[_customerAddress] = dividendTokenBalanceLedger_[_customerAddress].sub(_amountOfDivTokens);
dividendTokenBalanceLedger_[_toAddress] = dividendTokenBalanceLedger_[_toAddress].add(_amountOfDivTokens);
// Recipient inherits dividend percentage if they have not already selected one.
if (!userSelectedRate[_toAddress])
{
userSelectedRate[_toAddress] = true;
userDividendRate[_toAddress] = userDividendRate[_customerAddress];
}
// Update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens);
payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens);
uint length;
assembly {
length := extcodesize(_toAddress)
}
if (length > 0) {
// its a contract
// note: at ethereum update ALL addresses are contracts
ERC223Receiving receiver = ERC223Receiving(_toAddress);
receiver.tokenFallback(_from, _amountOfTokens, _data);
}
// Fire logging event.
emit Transfer(_customerAddress, _toAddress, _amountOfFrontEndTokens);
}
// Called from transferFrom. Always checks if _customerAddress has dividends.
function withdrawFrom(address _customerAddress)
internal
{
// Setup data
uint _dividends = theDividendsOf(false, _customerAddress);
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
// Fire logging event.
emit onWithdraw(_customerAddress, _dividends);
}
/*=======================
= RESET FUNCTIONS =
======================*/
function injectEther()
public
payable
onlyAdministrator
{
}
/*=======================
= MATHS FUNCTIONS =
======================*/
function toPowerOfThreeHalves(uint x) public pure returns (uint) {
// m = 3, n = 2
// sqrt(x^3)
return sqrt(x ** 3);
}
function toPowerOfTwoThirds(uint x) public pure returns (uint) {
// m = 2, n = 3
// cbrt(x^2)
return cbrt(x ** 2);
}
function sqrt(uint x) public pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function cbrt(uint x) public pure returns (uint y) {
uint z = (x + 1) / 3;
y = x;
while (z < y) {
y = z;
z = (x / (z * z) + 2 * z) / 3;
}
}
}
/*=======================
= INTERFACES =
======================*/
contract ZethrBankroll {
function receiveDividends() public payable {}
}
// File: contracts/Games/JackpotHolding.sol
/*
*
* Jackpot holding contract.
*
* This accepts token payouts from a game for every player loss,
* and on a win, pays out *half* of the jackpot to the winner.
*
* Jackpot payout should only be called from the game.
*
*/
contract JackpotHolding is ERC223Receiving {
/****************************
* FIELDS
****************************/
// How many times we've paid out the jackpot
uint public payOutNumber = 0;
// The amount to divide the token balance by for a pay out (defaults to half the token balance)
uint public payOutDivisor = 2;
// Holds the bankroll controller info
ZethrBankrollControllerInterface controller;
// Zethr contract
Zethr zethr;
/****************************
* CONSTRUCTOR
****************************/
constructor (address _controllerAddress, address _zethrAddress) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
zethr = Zethr(_zethrAddress);
}
function() public payable {}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/)
public
returns (bool)
{
// Do nothing, we can track the jackpot by this balance
}
/****************************
* VIEWS
****************************/
function getJackpotBalance()
public view
returns (uint)
{
// Half of this balance + half of jackpotBalance in each token bankroll
uint tempBalance;
for (uint i=0; i<7; i++) {
tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0;
}
tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0;
return tempBalance;
}
/****************************
* OWNER FUNCTIONS
****************************/
/** @dev Sets the pay out divisor
* @param _divisor The value to set the new divisor to
*/
function ownerSetPayOutDivisor(uint _divisor)
public
ownerOnly
{
require(_divisor != 0);
payOutDivisor = _divisor;
}
/** @dev Sets the address of the game controller
* @param _controllerAddress The new address of the controller
*/
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
/** @dev Transfers the jackpot to _to
* @param _to Address to send the jackpot tokens to
*/
function ownerWithdrawZth(address _to)
public
ownerOnly
{
uint balance = zethr.balanceOf(address(this));
zethr.transfer(_to, balance);
}
/** @dev Transfers any ETH received from dividends to _to
* @param _to Address to send the ETH to
*/
function ownerWithdrawEth(address _to)
public
ownerOnly
{
_to.transfer(address(this).balance);
}
/****************************
* GAME FUNCTIONS
****************************/
function gamePayOutWinner(address _winner)
public
gameOnly
{
// Call the payout function on all 7 token bankrolls
for (uint i=0; i<7; i++) {
controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor);
}
uint payOutAmount;
// Calculate pay out & pay out
if (zethr.balanceOf(address(this)) >= 1e10) {
payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor;
}
if (payOutAmount >= 1e10) {
zethr.transfer(_winner, payOutAmount);
}
// Increment the statistics fields
payOutNumber += 1;
// Emit jackpot event
emit JackpotPayOut(_winner, payOutNumber);
}
/****************************
* EVENTS
****************************/
event JackpotPayOut(
address winner,
uint payOutNumber
);
/****************************
* MODIFIERS
****************************/
// Only an owner can call this method (controller is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
// Only a game can call this method
modifier gameOnly()
{
require(controller.validGameAddresses(msg.sender));
_;
}
}
// File: contracts/Bankroll/ZethrGame.sol
/* Zethr Game Interface
*
* Contains the necessary functions to integrate with
* the Zethr Token bankrolls & the Zethr game ecosystem.
*
* Token Bankroll Functions:
* - execute
*
* Player Functions:
* - finish
*
* Bankroll Controller / Owner Functions:
* - pauseGame
* - resumeGame
* - set resolver percentage
* - set controller address
*
* Player/Token Bankroll Functions:
* - resolvePendingBets
*/
contract ZethrGame {
using SafeMath for uint;
using SafeMath for uint56;
// Default events:
event Result (address player, uint amountWagered, int amountOffset);
event Wager (address player, uint amount, bytes data);
// Queue of pending/unresolved bets
address[] pendingBetsQueue;
uint queueHead = 0;
uint queueTail = 0;
// Store each player's latest bet via mapping
mapping(address => BetBase) bets;
// Bet structures must start with this layout
struct BetBase {
// Must contain these in this order
uint56 tokenValue; // Multiply by 1e14 to get tokens
uint48 blockNumber;
uint8 tier;
// Game specific structures can add more after this
}
// Mapping of addresses to their *position* in the queue
// Zero = they aren't in the queue
mapping(address => uint) pendingBetsMapping;
// Holds the bankroll controller info
ZethrBankrollControllerInterface controller;
// Is the game paused?
bool paused;
// Minimum bet should always be >= 1
uint minBet = 1e18;
// Percentage that a resolver gets when he resolves bets for the house
uint resolverPercentage;
// Every game has a name
string gameName;
constructor (address _controllerAddress, uint _resolverPercentage, string _name) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
resolverPercentage = _resolverPercentage;
gameName = _name;
}
/** @dev Gets the max profit of this game as decided by the token bankroll
* @return uint The maximum profit
*/
function getMaxProfit()
public view
returns (uint)
{
return ZethrTokenBankrollInterface(msg.sender).getMaxProfit(address(this));
}
/** @dev Pauses the game, preventing anyone from placing bets
*/
function ownerPauseGame()
public
ownerOnly
{
paused = true;
}
/** @dev Resumes the game, allowing bets
*/
function ownerResumeGame()
public
ownerOnly
{
paused = false;
}
/** @dev Sets the percentage of the bets that a resolver gets when resolving tokens.
* @param _percentage The percentage as x/1,000,000 that the resolver gets
*/
function ownerSetResolverPercentage(uint _percentage)
public
ownerOnly
{
require(_percentage <= 1000000);
resolverPercentage = _percentage;
}
/** @dev Sets the address of the game controller
* @param _controllerAddress The new address of the controller
*/
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
// Every game should have a name
/** @dev Sets the name of the game
* @param _name The name of the game
*/
function ownerSetGameName(string _name)
ownerOnly
public
{
gameName = _name;
}
/** @dev Gets the game name
* @return The name of the game
*/
function getGameName()
public view
returns (string)
{
return gameName;
}
/** @dev Resolve expired bets in the queue. Gives a percentage of the house edge to the resolver as ZTH
* @param _numToResolve The number of bets to resolve.
* @return tokensEarned The number of tokens earned
* @return queueHead The new head of the queue
*/
function resolveExpiredBets(uint _numToResolve)
public
returns (uint tokensEarned_, uint queueHead_)
{
uint mQueue = queueHead;
uint head;
uint tail = (mQueue + _numToResolve) > pendingBetsQueue.length ? pendingBetsQueue.length : (mQueue + _numToResolve);
uint tokensEarned = 0;
for (head = mQueue; head < tail; head++) {
// Check the head of the queue to see if there is a resolvable bet
// This means the bet at the queue head is older than 255 blocks AND is not 0
// (However, if the address at the head is null, skip it, it's already been resolved)
if (pendingBetsQueue[head] == address(0x0)) {
continue;
}
if (bets[pendingBetsQueue[head]].blockNumber != 0 && block.number > 256 + bets[pendingBetsQueue[head]].blockNumber) {
// Resolve the bet
// finishBetfrom returns the *player* profit
// this will be negative if the player lost and the house won
// so flip it to get the house profit, if any
int sum = - finishBetFrom(pendingBetsQueue[head]);
// Tokens earned is a percentage of the loss
if (sum > 0) {
tokensEarned += (uint(sum).mul(resolverPercentage)).div(1000000);
}
// Queue-tail is always the "next" open spot, so queue head and tail will never overlap
} else {
// If we can't resolve a bet, stop going down the queue
break;
}
}
queueHead = head;
// Send the earned tokens to the resolver
if (tokensEarned >= 1e14) {
controller.gamePayoutResolver(msg.sender, tokensEarned);
}
return (tokensEarned, head);
}
/** @dev Finishes the bet of the sender, if it exists.
* @return int The total profit (positive or negative) earned by the sender
*/
function finishBet()
public
hasNotBetThisBlock(msg.sender)
returns (int)
{
return finishBetFrom(msg.sender);
}
/** @dev Resturns a random number
* @param _blockn The block number to base the random number off of
* @param _entropy Data to use in the random generation
* @param _index Data to use in the random generation
* @return randomNumber The random number to return
*/
function maxRandom(uint _blockn, address _entropy, uint _index)
private view
returns (uint256 randomNumber)
{
return uint256(keccak256(
abi.encodePacked(
blockhash(_blockn),
_entropy,
_index
)));
}
/** @dev Returns a random number
* @param _upper The upper end of the range, exclusive
* @param _blockn The block number to use for the random number
* @param _entropy An address to be used for entropy
* @param _index A number to get the next random number
* @return randomNumber The random number
*/
function random(uint256 _upper, uint256 _blockn, address _entropy, uint _index)
internal view
returns (uint256 randomNumber)
{
return maxRandom(_blockn, _entropy, _index) % _upper;
}
// Prevents the user from placing two bets in one block
modifier hasNotBetThisBlock(address _sender)
{
require(bets[_sender].blockNumber != block.number);
_;
}
// Requires that msg.sender is one of the token bankrolls
modifier bankrollOnly {
require(controller.isTokenBankroll(msg.sender));
_;
}
// Requires that the game is not paused
modifier isNotPaused {
require(!paused);
_;
}
// Requires that the bet given has max profit low enough
modifier betIsValid(uint _betSize, uint _tier, bytes _data) {
uint divRate = ZethrTierLibrary.getDivRate(_tier);
require(isBetValid(_betSize, divRate, _data));
_;
}
// Only an owner can call this method (controller is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
/** @dev Places a bet. Callable only by token bankrolls
* @param _player The player that is placing the bet
* @param _tokenCount The total number of tokens bet
* @param _divRate The dividend rate of the player
* @param _data The game-specific data, encoded in bytes-form
*/
function execute(address _player, uint _tokenCount, uint _divRate, bytes _data) public;
/** @dev Resolves the bet of the supplied player.
* @param _playerAddress The address of the player whos bet we are resolving
* @return int The total profit the player earned, positive or negative
*/
function finishBetFrom(address _playerAddress) internal returns (int);
/** @dev Determines if a supplied bet is valid
* @param _tokenCount The total number of tokens bet
* @param _divRate The dividend rate of the bet
* @param _data The game-specific bet data
* @return bool Whether or not the bet is valid
*/
function isBetValid(uint _tokenCount, uint _divRate, bytes _data) public view returns (bool);
}
// File: contracts/Games/ZethrBigWheel.sol
/* The actual game contract.
*
* This contract contains the actual game logic,
* including placing bets (execute), resolving bets,
* and resolving expired bets.
*/
contract ZethrBigWheel is ZethrGame {
using SafeMath for uint8;
/****************************
* GAME SPECIFIC
****************************/
// Slots-specific bet structure
struct Bet {
// Must contain these in this order
uint56 tokenValue;
uint48 blockNumber;
uint8 tier;
// Game specific
uint bets; // this is actually a uint40[5] array but because solidity fucks us over with storage writes we will explicitly convert this for solidity so we write to a single storage ONCE not 5 times
}
/****************************
* FIELDS
****************************/
// The holding contract for jackpot tokens
JackpotHolding public jackpotHoldingContract;
/****************************
* CONSTRUCTOR
****************************/
constructor (address _controllerAddress, uint _resolverPercentage, string _name)
ZethrGame(_controllerAddress, _resolverPercentage, _name)
public
{
}
/****************************
* USER METHODS
****************************/
/** @dev Retrieve the results of the last spin of a plyer, for web3 calls.
* @param _playerAddress The address of the player
*/
function getLastSpinOutput(address _playerAddress)
public view
returns (uint winAmount, uint lossAmount, uint jackpotAmount, uint jackpotWins, uint output)
{
// Cast to Bet and read from storage
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
// Safety check
require(playerBet.blockNumber != 0);
(winAmount, lossAmount, jackpotAmount, jackpotWins, output) = getSpinOutput(playerBet.blockNumber, _playerAddress, playerBet.bets);
return (winAmount, lossAmount, jackpotAmount, jackpotWins, output);
}
event WheelResult(
uint _blockNumber,
address _target,
uint40[5] _bets,
uint _winAmount,
uint _lossAmount,
uint _winCategory
);
/** @dev Retrieve the results of the spin, for web3 calls.
* @param _blockNumber The block number of the spin
* @param _target The address of the better
* @param _bets_notconverted Array (declared as uint as read from storage) of bets to place on x2,4x,8x,12x,24x
* @return winAmount The total number of tokens won
* @return lossAmount The total number of tokens lost
* @return jackpotAmount The total amount of tokens won in the jackpot
* @return output An array of all of the results of a multispin
*/
function getSpinOutput(uint _blockNumber, address _target, uint _bets_notconverted)
public view
returns (uint winAmount, uint lossAmount, uint jackpotAmount, uint jackpotWins, uint output)
{
uint40[5] memory _bets = uintToBetsArray(_bets_notconverted);
// If the block is more than 255 blocks old, we can't get the result
uint result;
if (block.number - _blockNumber > 255) {
// Can't win: default to an impossible number
result = 999997;
} else {
// Generate a result - random based ONLY on a past block (future when submitted).
result = random(999996, _blockNumber, _target, 0) + 1;
}
uint[5] memory betsMul;
betsMul[0] = uint(_bets[0]).mul(1e14);
betsMul[1] = uint(_bets[1]).mul(1e14);
betsMul[2] = uint(_bets[2]).mul(1e14);
betsMul[3] = uint(_bets[3]).mul(1e14);
betsMul[4] = uint(_bets[4]).mul(1e14);
lossAmount = betsMul[0] + betsMul[1] + betsMul[2] + betsMul[3] + betsMul[4];
// Result is between 1 and 999996
// 1 - 1 Jackpot
// 2 - 27027 25x
// 27028 - 108107 10x
// 108108 - 270269 6x
// 270270 - 513511 4x
// 513512 - 999996 2x
uint _winCategory = 0;
if (result < 2) {
jackpotWins++;
_winCategory = 99;
} else {
if (result < 27028) {
if (betsMul[4] > 0) {
// Player has won the 25x multiplier category!
_winCategory = 25;
winAmount = SafeMath.mul(betsMul[4], 25);
lossAmount -= betsMul[4];
}
} else if (result < 108108) {
if (betsMul[3] > 0) {
// Player has won the 10x multiplier category!
_winCategory = 10;
winAmount = SafeMath.mul(betsMul[3], 10);
lossAmount -= betsMul[3];
}
} else if (result < 270269) {
if (betsMul[2] > 0) {
// Player has won the 6x multiplier category!
_winCategory = 6;
winAmount = SafeMath.mul(betsMul[2], 6);
lossAmount -= betsMul[2];
}
} else if (result < 513512) {
if (betsMul[1] > 0) {
// Player has won the 4x multiplier category!
_winCategory = 4;
winAmount = SafeMath.mul(betsMul[1], 4);
lossAmount -= betsMul[1];
}
} else if (result < 999997) {
if (betsMul[0] > 0) {
// Player has won the 2x multiplier category!
_winCategory = 2;
winAmount = SafeMath.mul(betsMul[0], 2);
lossAmount -= betsMul[0];
}
}
jackpotAmount = lossAmount.div(100);
lossAmount -= jackpotAmount;
}
emit WheelResult(_blockNumber, _target, _bets, winAmount, lossAmount, _winCategory);
return (winAmount, lossAmount, jackpotAmount, jackpotWins, result);
}
/** @dev Retrieve the results of the spin, for contract calls.
* @param _blockNumber The block number of the spin
* @param _target The address of the better
* @param _bets Array of bets to place on x2,4x,8x,12x,24x
* @return winAmount The total number of tokens won
* @return lossAmount The total number of tokens lost
* @return jackpotAmount The total amount of tokens won in the jackpot
*/
function getSpinResults(uint _blockNumber, address _target, uint _bets)
public
returns (uint winAmount, uint lossAmount, uint jackpotAmount, uint jackpotWins)
{
(winAmount, lossAmount, jackpotAmount, jackpotWins,) = getSpinOutput(_blockNumber, _target, _bets);
}
/****************************
* OWNER METHODS
****************************/
/** @dev Set the address of the jackpot contract
* @param _jackpotAddress The address of the jackpot contract
*/
function ownerSetJackpotAddress(address _jackpotAddress)
public
ownerOnly
{
jackpotHoldingContract = JackpotHolding(_jackpotAddress);
}
/****************************
* INTERNALS
****************************/
/** @dev Returs the bet struct of a player
* @param _playerAddress The address of the player
* @return Bet The bet of the player
*/
function getBet(address _playerAddress)
internal view
returns (Bet storage)
{
// Cast BetBase to Bet
BetBase storage betBase = bets[_playerAddress];
Bet storage playerBet;
assembly {
// tmp is pushed onto stack and points to betBase slot in storage
let tmp := betBase_slot
// swap1 swaps tmp and playerBet pointers
swap1
}
// tmp is popped off the stack
// playerBet now points to betBase
return playerBet;
}
/** @dev Resturns a random number
* @param _blockn The block number to base the random number off of
* @param _entropy Data to use in the random generation
* @param _index Data to use in the random generation
* @return randomNumber The random number to return
*/
function maxRandom(uint _blockn, address _entropy, uint _index)
private view
returns (uint256 randomNumber)
{
return uint256(keccak256(
abi.encodePacked(
blockhash(_blockn),
_entropy,
_index
)));
}
/** @dev Returns a random number
* @param _upper The upper end of the range, exclusive
* @param _blockn The block number to use for the random number
* @param _entropy An address to be used for entropy
* @param _index A number to get the next random number
* @return randomNumber The random number
*/
function random(uint256 _upper, uint256 _blockn, address _entropy, uint _index)
internal view
returns (uint256 randomNumber)
{
return maxRandom(_blockn, _entropy, _index) % _upper;
}
/****************************
* OVERRIDDEN METHODS
****************************/
/** @dev Resolves the bet of the supplied player.
* @param _playerAddress The address of the player whos bet we are resolving
* @return totalProfit The total profit the player earned, positive or negative
*/
function finishBetFrom(address _playerAddress)
internal
returns (int /*totalProfit*/)
{
// Memory vars to hold data as we compute it
uint winAmount;
uint lossAmount;
uint jackpotAmount;
uint jackpotWins;
// Cast to Bet and read from storage
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
// Player should not be able to resolve twice!
require(playerBet.blockNumber != 0);
// Safety check
require(playerBet.blockNumber != 0);
playerBetInStorage.blockNumber = 0;
// Iterate over the number of spins and calculate totals:
// - player win amount
// - bankroll win amount
// - jackpot wins
(winAmount, lossAmount, jackpotAmount, jackpotWins) = getSpinResults(playerBet.blockNumber, _playerAddress, playerBet.bets);
// Figure out the token bankroll address
address tokenBankrollAddress = controller.getTokenBankrollAddressFromTier(playerBet.tier);
ZethrTokenBankrollInterface bankroll = ZethrTokenBankrollInterface(tokenBankrollAddress);
// Call into the bankroll to do some token accounting
bankroll.gameTokenResolution(winAmount, _playerAddress, jackpotAmount, address(jackpotHoldingContract), playerBet.tokenValue.mul(1e14));
// Pay out jackpot if won
if (jackpotWins > 0) {
for (uint x = 0; x < jackpotWins; x++) {
jackpotHoldingContract.gamePayOutWinner(_playerAddress);
}
}
// Grab the position of the player in the pending bets queue
uint index = pendingBetsMapping[_playerAddress];
// Remove the player from the pending bets queue by setting the address to 0x0
pendingBetsQueue[index] = address(0x0);
// Delete the player's bet by setting the mapping to zero
pendingBetsMapping[_playerAddress] = 0;
emit Result(_playerAddress, playerBet.tokenValue.mul(1e14), int(winAmount) - int(lossAmount) - int(jackpotAmount));
// Return all bet results + total *player* profit
return (int(winAmount) - int(lossAmount) - int(jackpotAmount));
}
/** @dev Places a bet. Callable only by token bankrolls
* @param _player The player that is placing the bet
* @param _tokenCount The total number of tokens bet
* @param _tier The div rate tier the player falls in
* @param _data The game-specific data, encoded in bytes-form
*/
function execute(address _player, uint _tokenCount, uint _tier, bytes _data)
isNotPaused
bankrollOnly
betIsValid(_tokenCount, _tier, _data)
hasNotBetThisBlock(_player)
public
{
Bet storage playerBet = getBet(_player);
// Check for a player bet and resolve if necessary
if (playerBet.blockNumber != 0) {
finishBetFrom(_player);
}
// Set bet information
playerBet.tokenValue = uint56(_tokenCount.div(1e14));
playerBet.blockNumber = uint48(block.number);
playerBet.tier = uint8(_tier);
require(_data.length == 32);
uint actual_data;
assembly{
actual_data := mload(add(_data, 0x20))
}
playerBet.bets = actual_data;
uint40[5] memory actual_bets = uintToBetsArray(actual_data);
// Sum of all bets should be the amount of tokens transferred
require((uint(actual_bets[0]) + uint(actual_bets[1]) + uint(actual_bets[2]) + uint(actual_bets[3]) + uint(actual_bets[4])).mul(1e14) == _tokenCount);
// Add player to the pending bets queue
pendingBetsQueue.length++;
pendingBetsQueue[queueTail] = _player;
queueTail++;
// Add the player's position in the queue to the pending bets mapping
pendingBetsMapping[_player] = queueTail - 1;
// Emit event
emit Wager(_player, _tokenCount, _data);
}
/** @dev Determines if a supplied bet is valid
* @param _data The game-specific bet data
* @return bool Whether or not the bet is valid
*/
function isBetValid(uint /*_tokenCount*/, uint /*_divRate*/, bytes _data)
public view
returns (bool)
{
uint actual_data;
assembly{
actual_data := mload(add(_data, 0x20))
}
uint40[5] memory bets = uintToBetsArray(actual_data);
uint bet2Max = bets[0] * 2;
uint bet4Max = bets[1] * 4;
uint bet6Max = bets[2] * 6;
uint bet10Max = bets[3] * 10;
uint bet25Max = bets[4] * 25;
uint max = bet2Max;
if (bet4Max > max) {
max = bet4Max;
}
if (bet6Max > max) {
max = bet6Max;
}
if (bet10Max > max) {
max = bet10Max;
}
if (bet25Max > max) {
max = bet25Max;
}
uint minBetDiv = minBet.div(1e14);
return (max*1e14 <= getMaxProfit())
&& ((bets[0]) >= minBetDiv || (bets[0]) == 0)
&& ((bets[1]) >= minBetDiv || (bets[1]) == 0)
&& ((bets[2]) >= minBetDiv || (bets[2]) == 0)
&& ((bets[3]) >= minBetDiv || (bets[3]) == 0)
&& ((bets[4]) >= minBetDiv || (bets[4]) == 0);
}
function betInputToBytes(uint40 bet1, uint40 bet2, uint40 bet3, uint40 bet4, uint40 bet5) pure public returns (bytes32){
bytes memory concat = (abi.encodePacked(uint56(0), bet1, bet2, bet3, bet4, bet5));
bytes32 output;
assembly{
output := mload(add(concat, 0x20))
}
return output;
}
function uintToBetsArray(uint input) public view returns (uint40[5]){
uint40[5] memory output;
uint trackme = (input);
for (uint i=4;; i--){
output[i] = uint40(trackme); // auto take the last 40 bits in memory
trackme /= 0x0000000000000000000000000000000000000000000000000000010000000000; // left shift 40 bits
if (i==0){
break;
}
}
return output;
}
function getPlayerBetData(address player) public view returns(uint40[5]){
uint betData = getBet(player).bets;
return (uintToBetsArray(betData));
}
} | Returns whether the target address is a contract 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. addr address to check return whether the target address is a contract/ 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. | function isContract(address addr) internal view returns (bool) {
uint size;
return size > 0;
}
| 1,241,664 |
./partial_match/1/0xbb963750b4e02e044E9b91A68Ef1Fb0d35787654/sources/Stakeable.sol | Expose the max reward ratio return The uint256 value of {_maxRewardRatio} | function maxRewardRatio()
public view returns (uint256) {
return _maxRewardRatio;
}
| 4,163,305 |
./partial_match/97/0xB618440C4D3c1a2750afB491bA3fe8b99505b01B/sources/LayerLock.sol | Initilaize a new campaign (can only be triggered by the factory contract) | function initilaize(uint[] calldata _data,address _token,address _owner_Address,uint _pool_rate,uint _lock_duration,uint _pancakeswap_rate) external returns (uint){
require(msg.sender == factory,'You are not allowed to initialize a new Campaign');
owner = _owner_Address;
softCap = _data[0];
hardCap = _data[1];
start_date = _data[2];
end_date = _data[3];
rate = _data[4];
min_allowed = _data[5];
max_allowed = _data[6];
token = _token;
pool_rate = _pool_rate;
lock_duration = _lock_duration;
pancakeswap_rate = _pancakeswap_rate;
}
| 11,441,677 |
./full_match/11155111/0x2c062707892eb463B22B4FFb3beB1cD69626eae2/sources/src/layercake/LayerCakeStorageManager.sol | Deploy new contract | function checkCreateStorageSlot(uint256 _timestamp)
private
returns (uint256 storageSlot)
{
uint256 thisStorageSlot;
uint256 latestStorageEpoch;
uint256 thisStorageEpoch;
bool newSlotRequired;
(thisStorageSlot, latestStorageEpoch, thisStorageEpoch, newSlotRequired) = getStorageSlot(_timestamp);
require(latestStorageEpoch - thisStorageEpoch < STORAGE_SLOTS/2, "CCSS1");
if (newSlotRequired) {
LayerCakeStorageSlot newLayerCakeStorageSlot = new LayerCakeStorageSlot(
address(this),
layerCakeDeployTime + (thisStorageEpoch * STORAGE_TIME),
layerCakeDeployTime + ((thisStorageEpoch + 1) * STORAGE_TIME)
);
layerCakeStorageSlots[thisStorageSlot] = address(newLayerCakeStorageSlot);
storageEpoch = thisStorageEpoch;
}
require(_timestamp >= LayerCakeStorageSlot(layerCakeStorageSlots[thisStorageSlot]).storageStartTime() &&
_timestamp < LayerCakeStorageSlot(layerCakeStorageSlots[thisStorageSlot]).storageEndTime(), "CCSS2");
return thisStorageSlot;
}
| 3,812,460 |
./full_match/4/0x12ee8FC27B7bdD2A75CA9a010CFb540046856e7A/sources/browser/Lottery2.sol | Send prize fund to the winner. Clears up info about last round./ | function sendPrizeToWinner() public {
require(!isRoundActive(), "Round must be finished first");
require(prizeFund > 0, "Prize fund is empty");
emit PrizeWithdrawed(lastInvestorAddress, prizeFund);
_tokenContract.transfer(lastInvestorAddress, prizeFund);
prizeFund = 0;
lastInvestedTime = 0;
lastInvestorAddress = address(0);
}
| 650,126 |
// File: @openzeppelin/contracts/GSN/Context.sol
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.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 {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}.
*/
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"));
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity 0.5.17;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant basisValue = 1000000000000000000;
/**
* Returns the ratio of the first argument to the second argument.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(basisValue);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* Returns multiplied the number by 10^18.
* This is used when there is a very large difference between the two numbers passed to the `outOf` function.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(basisValue);
}
/**
* Returns by changing the numerical value being emulated to the original number of digits.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(basisValue);
}
}
// File: contracts/src/common/interface/IGroup.sol
pragma solidity 0.5.17;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity 0.5.17;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// File: contracts/src/property/IProperty.sol
pragma solidity 0.5.17;
contract IProperty {
function author() external view returns (address);
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity 0.5.17;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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 = _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;
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity 0.5.17;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity 0.5.17;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity 0.5.17;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity 0.5.17;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/lockup/LockupStorage.sol
pragma solidity 0.5.17;
contract LockupStorage is UsingStorage {
using SafeMath for uint256;
uint256 public constant basis = 100000000000000000000000000000000;
//AllValue
function setStorageAllValue(uint256 _value) internal {
bytes32 key = getStorageAllValueKey();
eternalStorage().setUint(key, _value);
}
function getStorageAllValue() public view returns (uint256) {
bytes32 key = getStorageAllValueKey();
return eternalStorage().getUint(key);
}
function getStorageAllValueKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_allValue"));
}
//Value
function setStorageValue(
address _property,
address _sender,
uint256 _value
) internal {
bytes32 key = getStorageValueKey(_property, _sender);
eternalStorage().setUint(key, _value);
}
function getStorageValue(address _property, address _sender)
public
view
returns (uint256)
{
bytes32 key = getStorageValueKey(_property, _sender);
return eternalStorage().getUint(key);
}
function getStorageValueKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_value", _property, _sender));
}
//PropertyValue
function setStoragePropertyValue(address _property, uint256 _value)
internal
{
bytes32 key = getStoragePropertyValueKey(_property);
eternalStorage().setUint(key, _value);
}
function getStoragePropertyValue(address _property)
public
view
returns (uint256)
{
bytes32 key = getStoragePropertyValueKey(_property);
return eternalStorage().getUint(key);
}
function getStoragePropertyValueKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_propertyValue", _property));
}
//WithdrawalStatus
function setStorageWithdrawalStatus(
address _property,
address _from,
uint256 _value
) internal {
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
eternalStorage().setUint(key, _value);
}
function getStorageWithdrawalStatus(address _property, address _from)
public
view
returns (uint256)
{
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
return eternalStorage().getUint(key);
}
function getStorageWithdrawalStatusKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalStatus", _property, _sender)
);
}
//InterestPrice
function setStorageInterestPrice(address _property, uint256 _value)
internal
{
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
}
function getStorageInterestPrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getStorageInterestPriceKey(_property));
}
function getStorageInterestPriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_interestTotals", _property));
}
//LastInterestPrice
function setStorageLastInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastInterestPriceKey(_property, _user)
);
}
function getStorageLastInterestPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastLastInterestPrice", _property, _user)
);
}
//LastSameRewardsAmountAndBlock
function setStorageLastSameRewardsAmountAndBlock(
uint256 _amount,
uint256 _block
) internal {
uint256 record = _amount.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastSameRewardsAmountAndBlockKey(),
record
);
}
function getStorageLastSameRewardsAmountAndBlock()
public
view
returns (uint256 _amount, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageLastSameRewardsAmountAndBlockKey()
);
uint256 amount = record.div(basis);
uint256 blockNumber = record.sub(amount.mul(basis));
return (amount, blockNumber);
}
function getStorageLastSameRewardsAmountAndBlockKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock"));
}
//CumulativeGlobalRewards
function setStorageCumulativeGlobalRewards(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeGlobalRewardsKey(),
_value
);
}
function getStorageCumulativeGlobalRewards() public view returns (uint256) {
return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey());
}
function getStorageCumulativeGlobalRewardsKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeGlobalRewards"));
}
//LastCumulativeGlobalReward
function setStorageLastCumulativeGlobalReward(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user),
_value
);
}
function getStorageLastCumulativeGlobalReward(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user)
);
}
function getStorageLastCumulativeGlobalRewardKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_LastCumulativeGlobalReward",
_property,
_user
)
);
}
//LastCumulativePropertyInterest
function setStorageLastCumulativePropertyInterest(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativePropertyInterestKey(_property, _user),
_value
);
}
function getStorageLastCumulativePropertyInterest(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativePropertyInterestKey(_property, _user)
);
}
function getStorageLastCumulativePropertyInterestKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativePropertyInterest",
_property,
_user
)
);
}
//CumulativeLockedUpUnitAndBlock
function setStorageCumulativeLockedUpUnitAndBlock(
address _addr,
uint256 _unit,
uint256 _block
) internal {
uint256 record = _unit.mul(basis).add(_block);
eternalStorage().setUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr),
record
);
}
function getStorageCumulativeLockedUpUnitAndBlock(address _addr)
public
view
returns (uint256 _unit, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr)
);
uint256 unit = record.div(basis);
uint256 blockNumber = record.sub(unit.mul(basis));
return (unit, blockNumber);
}
function getStorageCumulativeLockedUpUnitAndBlockKey(address _addr)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_cumulativeLockedUpUnitAndBlock", _addr)
);
}
//CumulativeLockedUpValue
function setStorageCumulativeLockedUpValue(address _addr, uint256 _value)
internal
{
eternalStorage().setUint(
getStorageCumulativeLockedUpValueKey(_addr),
_value
);
}
function getStorageCumulativeLockedUpValue(address _addr)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageCumulativeLockedUpValueKey(_addr)
);
}
function getStorageCumulativeLockedUpValueKey(address _addr)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeLockedUpValue", _addr));
}
//PendingWithdrawal
function setStoragePendingInterestWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStoragePendingInterestWithdrawalKey(_property, _user),
_value
);
}
function getStoragePendingInterestWithdrawal(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStoragePendingInterestWithdrawalKey(_property, _user)
);
}
function getStoragePendingInterestWithdrawalKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_pendingInterestWithdrawal", _property, _user)
);
}
//DIP4GenesisBlock
function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
function getStorageDIP4GenesisBlock() public view returns (uint256) {
return eternalStorage().getUint(getStorageDIP4GenesisBlockKey());
}
function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_dip4GenesisBlock"));
}
//LastCumulativeLockedUpAndBlock
function setStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user,
uint256 _cLocked,
uint256 _block
) internal {
uint256 record = _cLocked.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user),
record
);
}
function getStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user
) public view returns (uint256 _cLocked, uint256 _block) {
uint256 record = eternalStorage().getUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user)
);
uint256 cLocked = record.div(basis);
uint256 blockNumber = record.sub(cLocked.mul(basis));
return (cLocked, blockNumber);
}
function getStorageLastCumulativeLockedUpAndBlockKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativeLockedUpAndBlock",
_property,
_user
)
);
}
//lastStakedInterestPrice
function setStorageLastStakedInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastStakedInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastStakedInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakedInterestPriceKey(_property, _user)
);
}
function getStorageLastStakedInterestPriceKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_lastStakedInterestPrice", _property, _user)
);
}
//lastStakesChangedCumulativeReward
function setStorageLastStakesChangedCumulativeReward(uint256 _value)
internal
{
eternalStorage().setUint(
getStorageLastStakesChangedCumulativeRewardKey(),
_value
);
}
function getStorageLastStakesChangedCumulativeReward()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakesChangedCumulativeRewardKey()
);
}
function getStorageLastStakesChangedCumulativeRewardKey()
private
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward"));
}
//LastCumulativeHoldersRewardPrice
function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders)
internal
{
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPriceKey(),
_holders
);
}
function getStorageLastCumulativeHoldersRewardPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPriceKey()
);
}
function getStorageLastCumulativeHoldersRewardPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice"));
}
//LastCumulativeInterestPrice
function setStorageLastCumulativeInterestPrice(uint256 _interest) internal {
eternalStorage().setUint(
getStorageLastCumulativeInterestPriceKey(),
_interest
);
}
function getStorageLastCumulativeInterestPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeInterestPriceKey()
);
}
function getStorageLastCumulativeInterestPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeInterestPrice"));
}
//LastCumulativeHoldersRewardAmountPerProperty
function setStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
),
_value
);
}
function getStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardAmountPerProperty",
_property
)
);
}
//LastCumulativeHoldersRewardPricePerProperty
function setStorageLastCumulativeHoldersRewardPricePerProperty(
address _property,
uint256 _price
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property),
_price
);
}
function getStorageLastCumulativeHoldersRewardPricePerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardPricePerProperty",
_property
)
);
}
}
// File: contracts/src/policy/IPolicy.sol
pragma solidity 0.5.17;
contract IPolicy {
function rewards(uint256 _lockups, uint256 _assets)
external
view
returns (uint256);
function holdersShare(uint256 _amount, uint256 _lockups)
external
view
returns (uint256);
function assetValue(uint256 _value, uint256 _lockups)
external
view
returns (uint256);
function authenticationFee(uint256 _assets, uint256 _propertyAssets)
external
view
returns (uint256);
function marketApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function policyApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function marketVotingBlocks() external view returns (uint256);
function policyVotingBlocks() external view returns (uint256);
function abstentionPenalty(uint256 _count) external view returns (uint256);
function lockUpBlocks() external view returns (uint256);
}
// File: contracts/src/allocator/IAllocator.sol
pragma solidity 0.5.17;
contract IAllocator {
function calculateMaxRewardsPerBlock() public view returns (uint256);
function beforeBalanceChange(
address _property,
address _from,
address _to
// solium-disable-next-line indentation
) external;
}
// File: contracts/src/lockup/ILegacyLockup.sol
pragma solidity 0.5.17;
contract ILegacyLockup {
function lockup(
address _from,
address _property,
uint256 _value
// solium-disable-next-line indentation
) external;
function update() public;
function cancel(address _property) external;
function withdraw(address _property) external;
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
)
public
view
returns (
// solium-disable-next-line indentation
uint256
);
function withdrawInterest(address _property) external;
}
// File: contracts/src/metrics/IMetricsGroup.sol
pragma solidity 0.5.17;
contract IMetricsGroup is IGroup {
function removeGroup(address _addr) external;
function totalIssuedMetrics() external view returns (uint256);
function getMetricsCountPerProperty(address _property)
public
view
returns (uint256);
function hasAssets(address _property) public view returns (bool);
}
// File: contracts/src/lockup/LegacyLockup.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* A contract that manages the staking of DEV tokens and calculates rewards.
* Staking and the following mechanism determines that reward calculation.
*
* Variables:
* -`M`: Maximum mint amount per block determined by Allocator contract
* -`B`: Number of blocks during staking
* -`P`: Total number of staking locked up in a Property contract
* -`S`: Total number of staking locked up in all Property contracts
* -`U`: Number of staking per account locked up in a Property contract
*
* Formula:
* Staking Rewards = M * B * (P / S) * (U / P)
*
* Note:
* -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted.
* -`B` is added every time the Ethereum block is created.
* - Only `U` and `B` are predictable variables.
* - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history.
* - Reward withdrawal always withdraws the total withdrawable amount.
*
* Scenario:
* - Assume `M` is fixed at 500
* - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100)
* - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100)
* - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100)
* - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV).
*/
contract LegacyLockup is
ILegacyLockup,
UsingConfig,
UsingValidator,
LockupStorage
{
using SafeMath for uint256;
using Decimals for uint256;
event Lockedup(address _from, address _property, uint256 _value);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Adds staking.
* Only the Dev contract can execute this function.
*/
function lockup(
address _from,
address _property,
uint256 _value
) external {
/**
* Validates the sender is Dev contract.
*/
addressValidator().validateAddress(msg.sender, config().token());
/**
* Validates _value is not 0.
*/
require(_value != 0, "illegal lockup value");
/**
* Validates the passed Property has greater than 1 asset.
*/
require(
IMetricsGroup(config().metricsGroup()).hasAssets(_property),
"unable to stake to unauthenticated property"
);
/**
* Refuses new staking when after cancel staking and until release it.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, _from) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Since the reward per block that can be withdrawn will change with the addition of staking,
* saves the undrawn withdrawable reward before addition it.
*/
updatePendingInterestWithdrawal(_property, _from);
/**
* Saves the variables at the time of staking to prepare for reward calculation.
*/
(, , , uint256 interest, ) = difference(_property, 0);
updateStatesAtLockup(_property, _from, interest);
/**
* Saves variables that should change due to the addition of staking.
*/
updateValues(true, _from, _property, _value);
emit Lockedup(_from, _property, _value);
}
/**
* Cancel staking.
* The staking amount can be withdrawn after the blocks specified by `Policy.lockUpBlocks` have passed.
*/
function cancel(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the sender is staking to the target Property.
*/
require(hasValue(_property, msg.sender), "dev token is not locked");
/**
* Validates not already been canceled.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, msg.sender) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Get `Policy.lockUpBlocks`, add it to the current block number, and saves that block number in `WithdrawalStatus`.
* Staking is cannot release until the block number saved in `WithdrawalStatus` is reached.
*/
uint256 blockNumber = IPolicy(config().policy()).lockUpBlocks();
blockNumber = blockNumber.add(block.number);
setStorageWithdrawalStatus(_property, msg.sender, blockNumber);
}
/**
* Withdraw staking.
* Releases canceled staking and transfer the staked amount to the sender.
*/
function withdraw(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the block number reaches the block number where staking can be released.
*/
require(possible(_property, msg.sender), "waiting for release");
/**
* Validates the sender is staking to the target Property.
*/
uint256 lockedUpValue = getStorageValue(_property, msg.sender);
require(lockedUpValue != 0, "dev token is not locked");
/**
* Since the increase of rewards will stop with the release of the staking,
* saves the undrawn withdrawable reward before releasing it.
*/
updatePendingInterestWithdrawal(_property, msg.sender);
/**
* Transfer the staked amount to the sender.
*/
IProperty(_property).withdraw(msg.sender, lockedUpValue);
/**
* Saves variables that should change due to the canceling staking..
*/
updateValues(false, msg.sender, _property, lockedUpValue);
/**
* Sets the staked amount to 0.
*/
setStorageValue(_property, msg.sender, 0);
/**
* Sets the cancellation status to not have.
*/
setStorageWithdrawalStatus(_property, msg.sender, 0);
}
/**
* Returns the current staking amount, and the block number in which the recorded last.
* These values are used to calculate the cumulative sum of the staking.
*/
function getCumulativeLockedUpUnitAndBlock(address _property)
private
view
returns (uint256 _unit, uint256 _block)
{
/**
* Get the current staking amount and the last recorded block number from the `CumulativeLockedUpUnitAndBlock` storage.
* If the last recorded block number is not 0, it is returns as it is.
*/
(
uint256 unit,
uint256 lastBlock
) = getStorageCumulativeLockedUpUnitAndBlock(_property);
if (lastBlock > 0) {
return (unit, lastBlock);
}
/**
* If the last recorded block number is 0, this function falls back as already staked before the current specs (before DIP4).
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*
* When the passed address is 0, the caller wants to know the total staking amount on the protocol,
* so gets the total staking amount from `AllValue` storage.
* When the address is other than 0, the caller wants to know the staking amount of a Property,
* so gets the staking amount from the `PropertyValue` storage.
*/
unit = _property == address(0)
? getStorageAllValue()
: getStoragePropertyValue(_property);
/**
* Staking pre-DIP4 will be treated as staked simultaneously with the DIP4 release.
* Therefore, the last recorded block number is the same as the DIP4 release block.
*/
lastBlock = getStorageDIP4GenesisBlock();
return (unit, lastBlock);
}
/**
* Returns the cumulative sum of the staking on passed address, the current staking amount,
* and the block number in which the recorded last.
* The latest cumulative sum can be calculated using the following formula:
* (current staking amount) * (current block number - last recorded block number) + (last cumulative sum)
*/
function getCumulativeLockedUp(address _property)
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* Gets the current staking amount and the last recorded block number from the `getCumulativeLockedUpUnitAndBlock` function.
*/
(uint256 unit, uint256 lastBlock) = getCumulativeLockedUpUnitAndBlock(
_property
);
/**
* Gets the last cumulative sum of the staking from `CumulativeLockedUpValue` storage.
*/
uint256 lastValue = getStorageCumulativeLockedUpValue(_property);
/**
* Returns the latest cumulative sum, current staking amount as a unit, and last recorded block number.
*/
return (
lastValue.add(unit.mul(block.number.sub(lastBlock))),
unit,
lastBlock
);
}
/**
* Returns the cumulative sum of the staking on the protocol totally, the current staking amount,
* and the block number in which the recorded last.
*/
function getCumulativeLockedUpAll()
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* If the 0 address is passed as a key, it indicates the entire protocol.
*/
return getCumulativeLockedUp(address(0));
}
/**
* Updates the `CumulativeLockedUpValue` and `CumulativeLockedUpUnitAndBlock` storage.
* This function expected to executes when the amount of staking as a unit changes.
*/
function updateCumulativeLockedUp(
bool _addition,
address _property,
uint256 _unit
) private {
address zero = address(0);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the passed Property address.
*/
(uint256 lastValue, uint256 lastUnit, ) = getCumulativeLockedUp(
_property
);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the protocol total.
*/
(uint256 lastValueAll, uint256 lastUnitAll, ) = getCumulativeLockedUp(
zero
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the passed Property address.
*/
setStorageCumulativeLockedUpValue(
_property,
_addition ? lastValue.add(_unit) : lastValue.sub(_unit)
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the protocol total.
*/
setStorageCumulativeLockedUpValue(
zero,
_addition ? lastValueAll.add(_unit) : lastValueAll.sub(_unit)
);
/**
* Adds or subtracts the staking amount to the staking unit for the passed Property address.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
_property,
_addition ? lastUnit.add(_unit) : lastUnit.sub(_unit),
block.number
);
/**
* Adds or subtracts the staking amount to the staking unit for the protocol total.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
zero,
_addition ? lastUnitAll.add(_unit) : lastUnitAll.sub(_unit),
block.number
);
}
/**
* Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block,
* and the last recorded block number.
* The cumulative sum of the maximum mint amount is always added.
* By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated.
*/
function update() public {
/**
* Gets the cumulative sum of the maximum mint amount and the maximum mint number per block.
*/
(uint256 _nextRewards, uint256 _amount) = dry();
/**
* Records each value and the latest block number.
*/
setStorageCumulativeGlobalRewards(_nextRewards);
setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
}
/**
* Updates the cumulative sum of the maximum mint amount when staking, the cumulative sum of staker reward as an interest of the target Property
* and the cumulative staking amount, and the latest block number.
*/
function updateStatesAtLockup(
address _property,
address _user,
uint256 _interest
) private {
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 _reward, ) = dry();
/**
* Records each value and the latest block number.
*/
if (isSingle(_property, _user)) {
setStorageLastCumulativeGlobalReward(_property, _user, _reward);
}
setStorageLastCumulativePropertyInterest(_property, _user, _interest);
(uint256 cLocked, , ) = getCumulativeLockedUp(_property);
setStorageLastCumulativeLockedUpAndBlock(
_property,
_user,
cLocked,
block.number
);
}
/**
* Returns the last cumulative staking amount of the passed Property address and the last recorded block number.
*/
function getLastCumulativeLockedUpAndBlock(address _property, address _user)
private
view
returns (uint256 _cLocked, uint256 _block)
{
/**
* Gets the values from `LastCumulativeLockedUpAndBlock` storage.
*/
(
uint256 cLocked,
uint256 blockNumber
) = getStorageLastCumulativeLockedUpAndBlock(_property, _user);
/**
* When the last recorded block number is 0, the block number at the time of the DIP4 release is returned as being staked at the same time as the DIP4 release.
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*/
if (blockNumber == 0) {
blockNumber = getStorageDIP4GenesisBlock();
}
return (cLocked, blockNumber);
}
/**
* Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block.
*/
function dry()
private
view
returns (uint256 _nextRewards, uint256 _amount)
{
/**
* Gets the latest mint amount per block from Allocator contract.
*/
uint256 rewardsAmount = IAllocator(config().allocator())
.calculateMaxRewardsPerBlock();
/**
* Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage.
*/
(
uint256 lastAmount,
uint256 lastBlock
) = getStorageLastSameRewardsAmountAndBlock();
/**
* If the recorded maximum mint amount per block and the result of the Allocator contract are different,
* the result of the Allocator contract takes precedence as a maximum mint amount per block.
*/
uint256 lastMaxRewards = lastAmount == rewardsAmount
? rewardsAmount
: lastAmount;
/**
* Calculates the difference between the latest block number and the last recorded block number.
*/
uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0;
/**
* Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount.
*/
uint256 additionalRewards = lastMaxRewards.mul(blocks);
uint256 nextRewards = getStorageCumulativeGlobalRewards().add(
additionalRewards
);
/**
* Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block.
*/
return (nextRewards, rewardsAmount);
}
/**
* Returns the latest theoretical cumulative sum of maximum mint amount, the holder's reward of the passed Property address and its unit price,
* and the staker's reward as interest and its unit price.
* The latest theoretical cumulative sum of maximum mint amount is got from `dry` function.
* The Holder's reward is a staking(delegation) reward received by the holder of the Property contract(token) according to the share.
* The unit price of the holder's reward is the reward obtained per 1 piece of Property contract(token).
* The staker rewards are rewards for staking users.
* The unit price of the staker reward is the reward per DEV token 1 piece that is staking.
*/
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
)
{
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 rewards, ) = dry();
/**
* Gets the cumulative sum of the staking amount of the passed Property address and
* the cumulative sum of the staking amount of the protocol total.
*/
(uint256 valuePerProperty, , ) = getCumulativeLockedUp(_property);
(uint256 valueAll, , ) = getCumulativeLockedUpAll();
/**
* Calculates the amount of reward that can be received by the Property from the ratio of the cumulative sum of the staking amount of the Property address
* and the cumulative sum of the staking amount of the protocol total.
* If the past cumulative sum of the maximum mint amount passed as the second argument is 1 or more,
* this result is the difference from that cumulative sum.
*/
uint256 propertyRewards = rewards.sub(_lastReward).mul(
valuePerProperty.mulBasis().outOf(valueAll)
);
/**
* Gets the staking amount and total supply of the Property and calls `Policy.holdersShare` function to calculates
* the holder's reward amount out of the total reward amount.
*/
uint256 lockedUpPerProperty = getStoragePropertyValue(_property);
uint256 totalSupply = ERC20Mintable(_property).totalSupply();
uint256 holders = IPolicy(config().policy()).holdersShare(
propertyRewards,
lockedUpPerProperty
);
/**
* The total rewards amount minus the holder reward amount is the staker rewards as an interest.
*/
uint256 interest = propertyRewards.sub(holders);
/**
* Returns each value and a unit price of each reward.
*/
return (
rewards,
holders,
holders.div(totalSupply),
interest,
lockedUpPerProperty > 0 ? interest.div(lockedUpPerProperty) : 0
);
}
/**
* Returns the staker reward as interest.
*/
function _calculateInterestAmount(address _property, address _user)
private
view
returns (uint256)
{
/**
* Gets the cumulative sum of the staking amount, current staking amount, and last recorded block number of the Property.
*/
(
uint256 cLockProperty,
uint256 unit,
uint256 lastBlock
) = getCumulativeLockedUp(_property);
/**
* Gets the cumulative sum of staking amount and block number of Property when the user staked.
*/
(
uint256 lastCLocked,
uint256 lastBlockUser
) = getLastCumulativeLockedUpAndBlock(_property, _user);
/**
* Get the amount the user is staking for the Property.
*/
uint256 lockedUpPerAccount = getStorageValue(_property, _user);
/**
* Gets the cumulative sum of the Property's staker reward when the user staked.
*/
uint256 lastInterest = getStorageLastCumulativePropertyInterest(
_property,
_user
);
/**
* Calculates the cumulative sum of the staking amount from the time the user staked to the present.
* It can be calculated by multiplying the staking amount by the number of elapsed blocks.
*/
uint256 cLockUser = lockedUpPerAccount.mul(
block.number.sub(lastBlockUser)
);
/**
* Determines if the user is the only staker to the Property.
*/
bool isOnly = unit == lockedUpPerAccount && lastBlock <= lastBlockUser;
/**
* If the user is the Property's only staker and the first staker, and the only staker on the protocol:
*/
if (isSingle(_property, _user)) {
/**
* Passing the cumulative sum of the maximum mint amount when staked, to the `difference` function,
* gets the staker reward amount that the user can receive from the time of staking to the present.
* In the case of the staking is single, the ratio of the Property and the user account for 100% of the cumulative sum of the maximum mint amount,
* so the difference cannot be calculated with the value of `LastCumulativePropertyInterest`.
* Therefore, it is necessary to calculate the difference using the cumulative sum of the maximum mint amounts at the time of staked.
*/
(, , , , uint256 interestPrice) = difference(
_property,
getStorageLastCumulativeGlobalReward(_property, _user)
);
/**
* Returns the result after adjusted decimals to 10^18.
*/
uint256 result = interestPrice
.mul(lockedUpPerAccount)
.divBasis()
.divBasis();
return result;
/**
* If not the single but the only staker:
*/
} else if (isOnly) {
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the difference in rewards that can be received by subtracting the Property's cumulative sum of staker rewards at the time of staking.
*/
uint256 result = interest >= lastInterest
? interest.sub(lastInterest).divBasis().divBasis()
: 0;
return result;
}
/**
* If the user is the Property's not the first staker and not the only staker:
*/
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the share of rewards that can be received by the user among Property's staker rewards.
* "Cumulative sum of the staking amount of the Property at the time of staking" is subtracted from "cumulative sum of the staking amount of the Property",
* and calculates the cumulative sum of staking amounts from the time of staking to the present.
* The ratio of the "cumulative sum of staking amount from the time the user staked to the present" to that value is the share.
*/
uint256 share = cLockUser.outOf(cLockProperty.sub(lastCLocked));
/**
* If the Property's staker reward is greater than the value of the `CumulativePropertyInterest` storage,
* calculates the difference and multiply by the share.
* Otherwise, it returns 0.
*/
uint256 result = interest >= lastInterest
? interest
.sub(lastInterest)
.mul(share)
.divBasis()
.divBasis()
.divBasis()
: 0;
return result;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return 0;
}
/**
* Gets the reward amount in saved without withdrawal.
*/
uint256 pending = getStoragePendingInterestWithdrawal(_property, _user);
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user);
/**
* Gets the latest withdrawal reward amount.
*/
uint256 amount = _calculateInterestAmount(_property, _user);
/**
* Returns the sum of all values.
*/
uint256 withdrawableAmount = amount
.add(pending) // solium-disable-next-line indentation
.add(legacy);
return withdrawableAmount;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableInterestAmount(
address _property,
address _user
) public view returns (uint256) {
uint256 amount = _calculateWithdrawableInterestAmount(_property, _user);
return amount;
}
/**
* Withdraws staking reward as an interest.
*/
function withdrawInterest(address _property) external {
/**
* Validates the target of staking is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Gets the withdrawable amount.
*/
uint256 value = _calculateWithdrawableInterestAmount(
_property,
msg.sender
);
/**
* Gets the cumulative sum of staker rewards of the passed Property address.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Validates rewards amount there are 1 or more.
*/
require(value > 0, "your interest amount is 0");
/**
* Sets the unwithdrawn reward amount to 0.
*/
setStoragePendingInterestWithdrawal(_property, msg.sender, 0);
/**
* Creates a Dev token instance.
*/
ERC20Mintable erc20 = ERC20Mintable(config().token());
/**
* Updates the staking status to avoid double rewards.
*/
updateStatesAtLockup(_property, msg.sender, interest);
__updateLegacyWithdrawableInterestAmount(_property, msg.sender);
/**
* Mints the reward.
*/
require(erc20.mint(msg.sender, value), "dev mint failed");
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Status updates with the addition or release of staking.
*/
function updateValues(
bool _addition,
address _account,
address _property,
uint256 _value
) private {
/**
* If added staking:
*/
if (_addition) {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(true, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
addAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
addPropertyValue(_property, _value);
/**
* Updates the user's current staking amount in the Property.
*/
addValue(_property, _account, _value);
/**
* If released staking:
*/
} else {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(false, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
subAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
subPropertyValue(_property, _value);
}
/**
* Since each staking amount has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Returns the staking amount of the protocol total.
*/
function getAllValue() external view returns (uint256) {
return getStorageAllValue();
}
/**
* Adds the staking amount of the protocol total.
*/
function addAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.add(_value);
setStorageAllValue(value);
}
/**
* Subtracts the staking amount of the protocol total.
*/
function subAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.sub(_value);
setStorageAllValue(value);
}
/**
* Returns the user's staking amount in the Property.
*/
function getValue(address _property, address _sender)
external
view
returns (uint256)
{
return getStorageValue(_property, _sender);
}
/**
* Adds the user's staking amount in the Property.
*/
function addValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.add(_value);
setStorageValue(_property, _sender, value);
}
/**
* Returns whether the user is staking in the Property.
*/
function hasValue(address _property, address _sender)
private
view
returns (bool)
{
uint256 value = getStorageValue(_property, _sender);
return value != 0;
}
/**
* Returns whether a single user has all staking share.
* This value is true when only one Property and one user is historically the only staker.
*/
function isSingle(address _property, address _user)
private
view
returns (bool)
{
uint256 perAccount = getStorageValue(_property, _user);
(uint256 cLockProperty, uint256 unitProperty, ) = getCumulativeLockedUp(
_property
);
(uint256 cLockTotal, , ) = getCumulativeLockedUpAll();
return perAccount == unitProperty && cLockProperty == cLockTotal;
}
/**
* Returns the staking amount of the Property.
*/
function getPropertyValue(address _property)
external
view
returns (uint256)
{
return getStoragePropertyValue(_property);
}
/**
* Adds the staking amount of the Property.
*/
function addPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
value = value.add(_value);
setStoragePropertyValue(_property, value);
}
/**
* Subtracts the staking amount of the Property.
*/
function subPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
uint256 nextValue = value.sub(_value);
setStoragePropertyValue(_property, nextValue);
}
/**
* Saves the latest reward amount as an undrawn amount.
*/
function updatePendingInterestWithdrawal(address _property, address _user)
private
{
/**
* Gets the latest reward amount.
*/
uint256 withdrawableAmount = _calculateWithdrawableInterestAmount(
_property,
_user
);
/**
* Saves the amount to `PendingInterestWithdrawal` storage.
*/
setStoragePendingInterestWithdrawal(
_property,
_user,
withdrawableAmount
);
/**
* Updates the reward amount of before DIP4 to prevent further addition it.
*/
__updateLegacyWithdrawableInterestAmount(_property, _user);
}
/**
* Returns whether the staking can be released.
*/
function possible(address _property, address _from)
private
view
returns (bool)
{
uint256 blockNumber = getStorageWithdrawalStatus(_property, _from);
if (blockNumber == 0) {
return false;
}
if (blockNumber <= block.number) {
return true;
} else {
if (IPolicy(config().policy()).lockUpBlocks() == 1) {
return true;
}
}
return false;
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the staking amount.
*/
function __legacyWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
uint256 _last = getStorageLastInterestPrice(_property, _user);
uint256 price = getStorageInterestPrice(_property);
uint256 priceGap = price.sub(_last);
uint256 lockedUpValue = getStorageValue(_property, _user);
uint256 value = priceGap.mul(lockedUpValue);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
) private {
uint256 interestPrice = getStorageInterestPrice(_property);
if (getStorageLastInterestPrice(_property, _user) != interestPrice) {
setStorageLastInterestPrice(_property, _user, interestPrice);
}
}
/**
* Updates the block number of the time of DIP4 release.
*/
function setDIP4GenesisBlock(uint256 _block) external onlyOwner {
/**
* Validates the value is not set.
*/
require(getStorageDIP4GenesisBlock() == 0, "already set the value");
/**
* Sets the value.
*/
setStorageDIP4GenesisBlock(_block);
}
}
// File: contracts/src/lockup/MigrateLockup.sol
pragma solidity 0.5.17;
contract MigrateLockup is LegacyLockup {
constructor(address _config) public LegacyLockup(_config) {}
function __initStakeOnProperty(
address _property,
address _user,
uint256 _cInterestPrice
) public onlyOwner {
require(
getStorageLastStakedInterestPrice(_property, _user) !=
_cInterestPrice,
"ALREADY EXISTS"
);
setStorageLastStakedInterestPrice(_property, _user, _cInterestPrice);
}
function __initLastStakeOnProperty(
address _property,
uint256 _cHoldersAmountPerProperty,
uint256 _cHoldersPrice
) public onlyOwner {
require(
getStorageLastCumulativeHoldersRewardAmountPerProperty(_property) !=
_cHoldersAmountPerProperty ||
getStorageLastCumulativeHoldersRewardPricePerProperty(
_property
) !=
_cHoldersPrice,
"ALREADY EXISTS"
);
setStorageLastCumulativeHoldersRewardAmountPerProperty(
_property,
_cHoldersAmountPerProperty
);
setStorageLastCumulativeHoldersRewardPricePerProperty(
_property,
_cHoldersPrice
);
}
function __initLastStake(
uint256 _cReward,
uint256 _cInterestPrice,
uint256 _cHoldersPrice
) public onlyOwner {
require(
getStorageLastStakesChangedCumulativeReward() != _cReward ||
getStorageLastCumulativeHoldersRewardPrice() !=
_cHoldersPrice ||
getStorageLastCumulativeInterestPrice() != _cInterestPrice,
"ALREADY EXISTS"
);
setStorageLastStakesChangedCumulativeReward(_cReward);
setStorageLastCumulativeHoldersRewardPrice(_cHoldersPrice);
setStorageLastCumulativeInterestPrice(_cInterestPrice);
}
} | Returns the last cumulative staking amount of the passed Property address and the last recorded block number./ Gets the values from `LastCumulativeLockedUpAndBlock` storage./ When the last recorded block number is 0, the block number at the time of the DIP4 release is returned as being staked at the same time as the DIP4 release./ | function getLastCumulativeLockedUpAndBlock(address _property, address _user)
private
view
returns (uint256 _cLocked, uint256 _block)
{
(
uint256 cLocked,
uint256 blockNumber
) = getStorageLastCumulativeLockedUpAndBlock(_property, _user);
if (blockNumber == 0) {
blockNumber = getStorageDIP4GenesisBlock();
}
return (cLocked, blockNumber);
}
| 10,078,159 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/IERC20.sol";
import "erc3156/contracts/interfaces/IERC3156FlashBorrower.sol";
import "erc3156/contracts/interfaces/IERC3156FlashLender.sol";
contract FlashBorrower is IERC3156FlashBorrower {
enum Action {NORMAL, TRANSFER, STEAL, REENTER, APPROVE}
IERC3156FlashLender public lender;
uint256 public flashBalance;
address public flashInitiator;
address public flashToken;
uint256 public flashAmount;
uint256 public flashFee;
constructor (IERC3156FlashLender lender_) {
lender = lender_;
}
/// @dev ERC-3156 Flash loan callback
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external override returns(bytes32) {
require(msg.sender == address(lender), "FlashBorrower: Untrusted lender");
(Action action) = abi.decode(data, (Action)); // Use this to unpack arbitrary data
flashInitiator = initiator;
flashToken = token;
flashAmount = amount;
flashFee = fee;
if (action == Action.NORMAL) {
flashBalance = IERC20(token).balanceOf(address(this));
} else if (action == Action.TRANSFER) {
flashBalance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(address(lender), amount + fee);
} else if (action == Action.STEAL) {
IERC20(token).transfer(address(0), amount);
} else if (action == Action.REENTER) {
flashBorrow(token, amount * 2, Action.NORMAL);
}
return keccak256("ERC3156FlashBorrower.onFlashLoan");
}
function flashBorrow(address token, uint256 amount, Action action) public {
bytes memory data = abi.encode(action);
uint256 allowance = IERC20(token).allowance(address(this), address(lender));
IERC20(token).approve(address(lender), allowance + amount + lender.flashFee(token, amount));
lender.flashLoan(this, token, amount, data);
}
}
| ERC-3156 Flash loan callback | function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external override returns(bytes32) {
require(msg.sender == address(lender), "FlashBorrower: Untrusted lender");
flashInitiator = initiator;
flashToken = token;
flashAmount = amount;
flashFee = fee;
if (action == Action.NORMAL) {
flashBalance = IERC20(token).balanceOf(address(this));
flashBalance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(address(lender), amount + fee);
IERC20(token).transfer(address(0), amount);
flashBorrow(token, amount * 2, Action.NORMAL);
}
return keccak256("ERC3156FlashBorrower.onFlashLoan");
}
| 2,545,412 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interface/AggregatorV3Interface.sol";
import "../interface/IDefxNFTFactory.sol";
import '../interface/ITokenBonusSharePool.sol';
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract BnbPriceUSDTPrediction is Ownable, Pausable,Initializable {
using SafeMath for uint256;
//
enum Position {Bull, Bear}
//期权周期
struct Round {
uint256 epoch; //index
uint256 startBlock; //开始区块
uint256 lockBlock; //锁的区块
uint256 endBlock; //结算区块
int256 lockPrice; //锁定价格
int256 closePrice; //结算价格
uint256 totalAmount; //投注总金额
uint256 bullAmount; //看涨金额
uint256 bearAmount; //看跌金额
uint256 rewardBaseCalAmount; //赢家投注金额
uint256 rewardAmount; //赢家金额
bool oracleCalled; //是否已经获取价格
}
//赌注即订单
struct BetInfo {
Position position; //看涨或者看跌
uint256 amount; //金额
bool claimed; // 是否需要领取
uint256 nftTokenId;
}
bool public genesisStartOnce = false; //是否调用初始化开始方法
bool public genesisLockOnce = false; //是否调用初始化锁定方法
uint256 public currentEpoch; //当前周期角标
uint256 public intervalBlocks; //100
uint256 public bufferBlocks; //15
address public adminAddress; //管理员地址
address public operatorAddress; //操作员地址
uint256 public oracleLatestRoundId;
uint256 public TOTAL_RATE; // 100%
uint256 public rewardRate; // 90% 赢家比率
uint256 public treasuryRate; // 10% 合约维护者佣金比率
uint256 public minBetAmount; //最小投资金额
uint256 public oracleUpdateAllowance; // seconds 允许价格相差的时间
mapping(uint256 => Round) public rounds; //期权周期mapping, currentEpoch
mapping(uint256 => mapping(address => BetInfo)) public ledger; //期权周期=>用户下注详细
mapping(address => uint256[]) public userRounds; //
IDefxNFTFactory public nftTokenFactory;
AggregatorV3Interface internal oracle; //预言机
ITokenBonusSharePool public bonusSharePool; //分红
IERC20 public betToken;
event StartRound(uint256 indexed epoch, uint256 blockNumber, uint256 intervalBlocks);
event LockRound(uint256 indexed epoch, uint256 blockNumber, int256 price);
event EndRound(uint256 indexed epoch, uint256 blockNumber, int256 price);
event BetBull(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId);
event BetBear(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId);
event Claim(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId);
event RatesUpdated(uint256 indexed epoch, uint256 rewardRate, uint256 treasuryRate);
event MinBetAmountUpdated(uint256 indexed epoch, uint256 minBetAmount);
event RewardsCalculated(uint256 indexed epoch, uint256 rewardBaseCalAmount, uint256 rewardAmount, uint256 treasuryAmount);
event Pause(uint256 epoch);
event Unpause(uint256 epoch);
modifier onlyAdmin() {
require(msg.sender == adminAddress, "admin: wut?");
_;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress, "operator: wut?");
_;
}
modifier onlyAdminOrOperator() {
require(msg.sender == adminAddress || msg.sender == operatorAddress, "admin | operator: wut?");
_;
}
modifier notContract() {
require(!_isContract(msg.sender), "contract not allowed");
require(msg.sender == tx.origin, "proxy contract not allowed");
_;
}
function initialize(
address _betToken,
AggregatorV3Interface _oracle,
address _adminAddress,
address _operatorAddress,
uint256 _intervalBlocks,
uint256 _bufferBlocks,
uint256 _minBetAmount,
uint256 _TOTAL_RATE,
uint256 _rewardRate,
uint256 _treasuryRate,
uint256 _oracleUpdateAllowance,
IDefxNFTFactory _nftTokenFactory) public initializer {
oracle = _oracle;
betToken = IERC20(_betToken);
adminAddress = _adminAddress;
operatorAddress = _operatorAddress;
intervalBlocks = _intervalBlocks;
bufferBlocks = _bufferBlocks;
minBetAmount = _minBetAmount;
TOTAL_RATE = _TOTAL_RATE;
rewardRate = _rewardRate;
treasuryRate = _treasuryRate;
oracleUpdateAllowance = _oracleUpdateAllowance;
nftTokenFactory = _nftTokenFactory;
}
/**
* @dev set admin address
* callable by owner
*/
function setAdmin(address _adminAddress) external onlyAdmin {
require(_adminAddress != address(0), "Cannot be zero address");
adminAddress = _adminAddress;
}
/**
* @dev set operator address
* callable by admin
*/
function setOperator(address _operatorAddress) external onlyAdmin {
require(_operatorAddress != address(0), "Cannot be zero address");
operatorAddress = _operatorAddress;
}
/**
* @dev set interval blocks
* callable by admin
*/
function setIntervalBlocks(uint256 _intervalBlocks) external onlyAdmin {
intervalBlocks = _intervalBlocks;
}
/**
* @dev set buffer blocks
* callable by admin
*/
function setBufferBlocks(uint256 _bufferBlocks) external onlyAdmin {
require(_bufferBlocks <= intervalBlocks, "Cannot be more than intervalBlocks");
bufferBlocks = _bufferBlocks;
}
/**
* @dev set Oracle address
* callable by admin
*/
function setOracle(address _oracle) external onlyAdmin {
require(_oracle != address(0), "Cannot be zero address");
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev set oracle update allowance
* callable by admin
*/
function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external onlyAdmin {
oracleUpdateAllowance = _oracleUpdateAllowance;
}
/**
* @dev set reward rate /设置盈利率
* callable by admin
*/
function setRewardRate(uint256 _rewardRate) external onlyAdmin whenPaused{
require(_rewardRate <= TOTAL_RATE, "rewardRate cannot be more than 100%");
rewardRate = _rewardRate;
treasuryRate = TOTAL_RATE.sub(_rewardRate);
emit RatesUpdated(currentEpoch, rewardRate, treasuryRate);
}
/**
* @dev set treasury rate
* callable by admin
*/
function setTreasuryRate(uint256 _treasuryRate) external onlyAdmin {
require(_treasuryRate <= TOTAL_RATE, "treasuryRate cannot be more than 100%");
rewardRate = TOTAL_RATE.sub(_treasuryRate);
treasuryRate = _treasuryRate;
emit RatesUpdated(currentEpoch, rewardRate, treasuryRate);
}
/**
* @dev set minBetAmount
* callable by admin
*/
function setMinBetAmount(uint256 _minBetAmount) external onlyAdmin {
minBetAmount = _minBetAmount;
emit MinBetAmountUpdated(currentEpoch, minBetAmount);
}
function setBonusSharePool(address _bonusSharePool) external onlyAdmin{
bonusSharePool = ITokenBonusSharePool(_bonusSharePool);
}
function setBetToken(address _betToken) external onlyAdmin {
betToken = IERC20(_betToken);
}
/**
* @dev Start genesis round/
*/
function genesisStartRound() external onlyAdminOrOperator whenNotPaused {
require(!genesisStartOnce, "Can only run genesisStartRound once");
currentEpoch = currentEpoch + 1;
_startRound(currentEpoch, getRoundStartBlock());
genesisStartOnce = true;
}
/**
* @dev Lock genesis round/
*/
function genesisLockRound() external onlyAdminOrOperator whenNotPaused {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
require(!genesisLockOnce, "Can only run genesisLockRound once");
require(
block.number <= rounds[currentEpoch].lockBlock.add(bufferBlocks),
"Can only lock round within bufferBlocks"
);
int256 currentPrice = _getPriceFromOracle();
_safeLockRound(currentEpoch, currentPrice);
currentEpoch = currentEpoch + 1;
_startRound(currentEpoch, getRoundStartBlock());
genesisLockOnce = true;
}
/**
*
* @dev Start the next round n, lock price for round n-1, end round n-2
*/
function executeRound() external onlyAdminOrOperator whenNotPaused {
require(
genesisStartOnce && genesisLockOnce,
"Can only run after genesisStartRound and genesisLockRound is triggered"
);
int256 currentPrice = _getPriceFromOracle();
// CurrentEpoch refers to previous round (n-1)
_safeLockRound(currentEpoch, currentPrice);
_safeEndRound(currentEpoch - 1, currentPrice);
_calculateRewards(currentEpoch - 1);
// Increment currentEpoch to current round (n)
currentEpoch = currentEpoch + 1;
_safeStartRound(currentEpoch);
if(currentEpoch >= 5 && rounds[currentEpoch - 5].totalAmount == 0) {
delete rounds[currentEpoch - 5];
}
}
/**
* @dev Bet bear position
*/
function betBear(uint256 amount) external payable whenNotPaused notContract {
require(_bettable(currentEpoch), "Round not bettable");
require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount");
require(betToken.transferFrom(msg.sender, address(this), amount), "transferFrom error");
require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round");
// Update round data
Round storage round = rounds[currentEpoch];
round.totalAmount = round.totalAmount.add(amount);
round.bearAmount = round.bearAmount.add(amount);
// Update user data
BetInfo storage betInfo = ledger[currentEpoch][msg.sender];
betInfo.position = Position.Bear;
betInfo.amount = amount;
betInfo.nftTokenId = 0;
userRounds[msg.sender].push(currentEpoch);
uint256 fee = betInfo.amount.mul(treasuryRate).div(TOTAL_RATE);
bonusSharePool.predictionBet(msg.sender, amount, fee);
emit BetBear(msg.sender, currentEpoch, amount, betInfo.nftTokenId);
}
/**
* @dev Bet bull position
*/
function betBull(uint256 amount) external payable whenNotPaused notContract {
require(_bettable(currentEpoch), "Round not bettable");
require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount");
require(betToken.transferFrom(msg.sender, address(this), amount), "transferFrom error");
require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round");
// Update round data
Round storage round = rounds[currentEpoch];
round.totalAmount = round.totalAmount.add(amount);
round.bullAmount = round.bullAmount.add(amount);
// Update user data
BetInfo storage betInfo = ledger[currentEpoch][msg.sender];
betInfo.position = Position.Bull;
betInfo.amount = amount;
betInfo.nftTokenId = 0;
userRounds[msg.sender].push(currentEpoch);
uint256 fee = betInfo.amount.mul(treasuryRate).div(TOTAL_RATE);
bonusSharePool.predictionBet(msg.sender, amount, fee);
emit BetBull(msg.sender, currentEpoch, amount, betInfo.nftTokenId);
}
/**
* 结算收益
* @dev Claim reward
*/
function claim(uint256 epoch) external payable notContract returns(uint256){
require(rounds[epoch].startBlock != 0, "Round has not started");
require(block.number > rounds[epoch].endBlock, "Round has not ended");
require(!ledger[epoch][msg.sender].claimed, "Rewards claimed");
require(ledger[epoch][msg.sender].amount > 0, "not bet");
BetInfo storage betInfo = ledger[epoch][msg.sender];
uint256 reward;
uint256 nftToken = 0;
// Round valid, claim rewards
if (rounds[epoch].oracleCalled) {
if(claimable(epoch, msg.sender)) {
Round memory round = rounds[epoch];
reward = ledger[epoch][msg.sender].amount.mul(round.rewardAmount).div(round.rewardBaseCalAmount);
require(betToken.transfer(msg.sender, reward), "transfer error");
} else {
betInfo.nftTokenId = nftTokenFactory.doMint(msg.sender, currentEpoch, betInfo.amount);
nftToken = betInfo.nftTokenId;
}
}
// Round invalid, refund bet amount
else {
require(refundable(epoch, msg.sender), "Not eligible for refund");
reward = ledger[epoch][msg.sender].amount.mul(rewardRate).div(TOTAL_RATE);
require(betToken.transfer(msg.sender, reward), "transfer error");
}
betInfo.claimed = true;
emit Claim(msg.sender, epoch, reward, betInfo.nftTokenId);
return nftToken;
}
/**
* @dev called by the admin to pause, triggers stopped state
*/
function pause() public onlyAdminOrOperator whenNotPaused {
_pause();
emit Pause(currentEpoch);
}
/**
* @dev called by the admin to unpause, returns to normal state
* Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis
*/
function unpause() public onlyAdminOrOperator whenPaused {
genesisStartOnce = false;
genesisLockOnce = false;
_unpause();
emit Unpause(currentEpoch);
}
/**
* @dev Return round epochs that a user has participated
*/
function getUserRounds(
address user,
uint256 cursor,
uint256 size
) external view returns (uint256[] memory, uint256) {
uint256 length = size;
if (length > userRounds[user].length - cursor) {
length = userRounds[user].length - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = userRounds[user][cursor + i];
}
return (values, cursor + length);
}
/**
* @dev Get the claimable stats of specific epoch and user account
*/
function claimable(uint256 epoch, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[epoch][user];
Round memory round = rounds[epoch];
if (round.lockPrice == round.closePrice) {
return false;
}
return
round.oracleCalled &&
((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) ||
(round.closePrice < round.lockPrice && betInfo.position == Position.Bear));
}
/**
* @dev Get the refundable stats of specific epoch and user account
*/
function refundable(uint256 epoch, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[epoch][user];
Round memory round = rounds[epoch];
return !round.oracleCalled && block.number > round.endBlock.add(bufferBlocks) && betInfo.amount != 0;
}
function indexRound(uint256 epoch) external view
returns(
uint256 startBlock,
uint256 lockBlock,
uint256 endBlock,
bool oracleCalled
) {
if(epoch == 0) {
epoch = currentEpoch;
}
Round memory round = rounds[epoch];
return (round.startBlock, round.lockBlock, round.endBlock, round.oracleCalled);
}
/**
* @dev Start round
* Previous round n-2 must end
*/
function _safeStartRound(uint256 epoch) internal {
uint256 startBlock = getRoundStartBlock();
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
require(rounds[epoch - 2].endBlock != 0, "Can only start round after round n-2 has ended");
require(startBlock >= rounds[epoch - 2].lockBlock, "Can only start new round after round n-2 endBlock");
_startRound(epoch, startBlock);
}
function _startRound(uint256 epoch, uint256 startBlock) internal {
Round storage round = rounds[epoch];
round.startBlock = startBlock;
round.lockBlock = startBlock.add(intervalBlocks);
round.endBlock = startBlock.add(intervalBlocks * 2);
round.epoch = epoch;
round.totalAmount = 0;
emit StartRound(epoch, startBlock, intervalBlocks);
}
/**
* @dev Lock round
*/
function _safeLockRound(uint256 epoch, int256 price) internal {
require(rounds[epoch].startBlock != 0, "Can only lock round after round has started");
require(block.number >= rounds[epoch].lockBlock, "Can only lock round after lockBlock");
require(block.number <= rounds[epoch].lockBlock.add(bufferBlocks), "Can only lock round within bufferBlocks");
_lockRound(epoch, price);
}
function _lockRound(uint256 epoch, int256 price) internal {
Round storage round = rounds[epoch];
round.lockPrice = price;
emit LockRound(epoch, block.number, round.lockPrice);
}
/**
* @dev End round
*/
function _safeEndRound(uint256 epoch, int256 price) internal {
require(rounds[epoch].lockBlock != 0, "Can only end round after round has locked");
require(block.number.add(intervalBlocks) >= rounds[epoch].endBlock, "Can only end round after endBlock");
require(block.number <= rounds[epoch].endBlock.add(bufferBlocks), "Can only end round within bufferBlocks");
_endRound(epoch, price);
}
function _endRound(uint256 epoch, int256 price) internal {
Round storage round = rounds[epoch];
round.closePrice = price;
round.oracleCalled = true;
emit EndRound(epoch, block.number, round.closePrice);
}
/**
* @dev Calculate rewards for round
*/
function _calculateRewards(uint256 epoch) internal {
require(rewardRate.add(treasuryRate) == TOTAL_RATE, "rewardRate and treasuryRate must add up to TOTAL_RATE");
require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated");
Round storage round = rounds[epoch];
uint256 rewardBaseCalAmount;
uint256 rewardAmount;
// Bull wins
if (round.closePrice > round.lockPrice) {
rewardBaseCalAmount = round.bullAmount;
rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE);
}
// Bear wins
else if (round.closePrice < round.lockPrice) {
rewardBaseCalAmount = round.bearAmount;
rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE);
}
// House wins
else {
rewardBaseCalAmount = 0;
rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE);
if(rewardAmount > 0) {
bonusSharePool.predictionBet(address(0x0), 0, rewardAmount);
}
}
round.rewardBaseCalAmount = rewardBaseCalAmount;
round.rewardAmount = rewardAmount;
emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, 0);
}
/**
*
*/
function approveToStakingAddress() public onlyAdminOrOperator{
betToken.approve(address(bonusSharePool), ~uint256(0));
}
/**
* @dev Get latest recorded price from oracle
* If it falls below allowed buffer or has not updated, it would be invalid
*/
function _getPriceFromOracle() internal returns (int256) {
uint256 leastAllowedTimestamp = block.timestamp.add(oracleUpdateAllowance);
(uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData();
require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance");
require(roundId > oracleLatestRoundId, "Oracle update roundId must be larger than oracleLatestRoundId");
oracleLatestRoundId = uint256(roundId);
return price;
}
function _safeTransferBNB(address to, uint256 value) internal {
(bool success, ) = to.call{gas: 23000, value: value}("");
require(success, "TransferHelper: BNB_TRANSFER_FAILED");
}
function _isContract(address addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
/**
* @dev Determine if a round is valid for receiving bets
* Round must have started and locked
* Current block must be within startBlock and endBlock
*/
function _bettable(uint256 epoch) internal view returns (bool) {
return
rounds[epoch].startBlock != 0 &&
rounds[epoch].lockBlock != 0 &&
block.number >= rounds[epoch].startBlock &&
block.number < rounds[epoch].lockBlock;
}
//获取整点区块
function getRoundStartBlock() public view returns(uint256) {
uint256 timeInterval = intervalBlocks * 3;
uint256 mod = block.timestamp.mod(timeInterval);
uint256 inBlock = mod.div(3);
uint256 blockNumber = block.number;
if(inBlock > 10 && blockNumber > inBlock) {
return blockNumber - inBlock;
}
return blockNumber;
}
}
| Start genesis round// | function genesisStartRound() external onlyAdminOrOperator whenNotPaused {
require(!genesisStartOnce, "Can only run genesisStartRound once");
currentEpoch = currentEpoch + 1;
_startRound(currentEpoch, getRoundStartBlock());
genesisStartOnce = true;
}
| 5,361,291 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../interfaces/IKernel.sol";
import "../libraries/LibKernelStorage.sol";
import "../libraries/LibOwnership.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract KernelFacet {
using SafeMath for uint256;
uint256 constant public MAX_LOCK = 365 days;
uint256 constant BASE_MULTIPLIER = 1e18;
event Deposit(address indexed user, uint256 amount, uint256 newBalance);
event Withdraw(address indexed user, uint256 amountWithdrew, uint256 amountLeft);
event Lock(address indexed user, uint256 timestamp);
event Delegate(address indexed from, address indexed to);
event DelegatedPowerIncreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);
event DelegatedPowerDecreased(address indexed from, address indexed to, uint256 amount, uint256 to_newDelegatedPower);
function initKernel(address _leag, address _rewards) public {
require(_leag != address(0), "LEAG address must not be 0x0");
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
require(!ds.initialized, "Kernel: already initialized");
LibOwnership.enforceIsContractOwner();
ds.initialized = true;
ds.leag = IERC20(_leag);
ds.rewards = IRewards(_rewards);
}
// deposit allows a user to add more leag to his staked balance
function deposit(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
uint256 allowance = ds.leag.allowance(msg.sender, address(this));
require(allowance >= amount, "Token allowance too small");
// this must be called before the user's balance is updated so the rewards contract can calculate
// the amount owed correctly
if (address(ds.rewards) != address(0)) {
ds.rewards.registerUserAction(msg.sender);
}
uint256 newBalance = balanceOf(msg.sender).add(amount);
_updateUserBalance(ds.userStakeHistory[msg.sender], newBalance);
_updateLockedLeag(leagStakedAtTs(block.timestamp).add(amount));
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).add(amount);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerIncreased(msg.sender, delegatedTo, amount, newDelegatedPower);
}
ds.leag.transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, newBalance);
}
// withdraw allows a user to withdraw funds if the balance is not locked
function withdraw(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
require(userLockedUntil(msg.sender) <= block.timestamp, "User balance is locked");
uint256 balance = balanceOf(msg.sender);
require(balance >= amount, "Insufficient balance");
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
// this must be called before the user's balance is updated so the rewards contract can calculate
// the amount owed correctly
if (address(ds.rewards) != address(0)) {
ds.rewards.registerUserAction(msg.sender);
}
_updateUserBalance(ds.userStakeHistory[msg.sender], balance.sub(amount));
_updateLockedLeag(leagStakedAtTs(block.timestamp).sub(amount));
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(amount);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerDecreased(msg.sender, delegatedTo, amount, newDelegatedPower);
}
ds.leag.transfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, balance.sub(amount));
}
// lock a user's currently staked balance until timestamp & add the bonus to his voting power
function lock(uint256 timestamp) public {
require(timestamp > block.timestamp, "Timestamp must be in the future");
require(timestamp <= block.timestamp + MAX_LOCK, "Timestamp too big");
require(balanceOf(msg.sender) > 0, "Sender has no balance");
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
LibKernelStorage.Stake[] storage checkpoints = ds.userStakeHistory[msg.sender];
LibKernelStorage.Stake storage currentStake = checkpoints[checkpoints.length - 1];
require(timestamp > currentStake.expiryTimestamp, "New timestamp lower than current lock timestamp");
_updateUserLock(checkpoints, timestamp);
emit Lock(msg.sender, timestamp);
}
function depositAndLock(uint256 amount, uint256 timestamp) public {
deposit(amount);
lock(timestamp);
}
// delegate allows a user to delegate his voting power to another user
function delegate(address to) public {
require(msg.sender != to, "Can't delegate to self");
uint256 senderBalance = balanceOf(msg.sender);
require(senderBalance > 0, "No balance to delegate");
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
emit Delegate(msg.sender, to);
address delegatedTo = userDelegatedTo(msg.sender);
if (delegatedTo != address(0)) {
uint256 newDelegatedPower = delegatedPower(delegatedTo).sub(senderBalance);
_updateDelegatedPower(ds.delegatedPowerHistory[delegatedTo], newDelegatedPower);
emit DelegatedPowerDecreased(msg.sender, delegatedTo, senderBalance, newDelegatedPower);
}
if (to != address(0)) {
uint256 newDelegatedPower = delegatedPower(to).add(senderBalance);
_updateDelegatedPower(ds.delegatedPowerHistory[to], newDelegatedPower);
emit DelegatedPowerIncreased(msg.sender, to, senderBalance, newDelegatedPower);
}
_updateUserDelegatedTo(ds.userStakeHistory[msg.sender], to);
}
// stopDelegate allows a user to take back the delegated voting power
function stopDelegate() public {
return delegate(address(0));
}
// balanceOf returns the current LEAG balance of a user (bonus not included)
function balanceOf(address user) public view returns (uint256) {
return balanceAtTs(user, block.timestamp);
}
// balanceAtTs returns the amount of LEAG that the user currently staked (bonus NOT included)
function balanceAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibKernelStorage.Stake memory stake = stakeAtTs(user, timestamp);
return stake.amount;
}
// stakeAtTs returns the Stake object of the user that was valid at `timestamp`
function stakeAtTs(address user, uint256 timestamp) public view returns (LibKernelStorage.Stake memory) {
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
LibKernelStorage.Stake[] storage stakeHistory = ds.userStakeHistory[user];
if (stakeHistory.length == 0 || timestamp < stakeHistory[0].timestamp) {
return LibKernelStorage.Stake(block.timestamp, 0, block.timestamp, address(0));
}
uint256 min = 0;
uint256 max = stakeHistory.length - 1;
if (timestamp >= stakeHistory[max].timestamp) {
return stakeHistory[max];
}
// binary search of the value in the array
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (stakeHistory[mid].timestamp <= timestamp) {
min = mid;
} else {
max = mid - 1;
}
}
return stakeHistory[min];
}
// votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block
function votingPower(address user) public view returns (uint256) {
return votingPowerAtTs(user, block.timestamp);
}
// votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time
function votingPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibKernelStorage.Stake memory stake = stakeAtTs(user, timestamp);
uint256 ownVotingPower;
// if the user delegated his voting power to another user, then he doesn't have any voting power left
if (stake.delegatedTo != address(0)) {
ownVotingPower = 0;
} else {
uint256 balance = stake.amount;
uint256 multiplier = _stakeMultiplier(stake, timestamp);
ownVotingPower = balance.mul(multiplier).div(BASE_MULTIPLIER);
}
uint256 delegatedVotingPower = delegatedPowerAtTs(user, timestamp);
return ownVotingPower.add(delegatedVotingPower);
}
// leagStaked returns the total raw amount of LEAG staked at the current block
function leagStaked() public view returns (uint256) {
return leagStakedAtTs(block.timestamp);
}
// leagStakedAtTs returns the total raw amount of LEAG users have deposited into the contract
// it does not include any bonus
function leagStakedAtTs(uint256 timestamp) public view returns (uint256) {
return _checkpointsBinarySearch(LibKernelStorage.kernelStorage().leagStakedHistory, timestamp);
}
// delegatedPower returns the total voting power that a user received from other users
function delegatedPower(address user) public view returns (uint256) {
return delegatedPowerAtTs(user, block.timestamp);
}
// delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time
function delegatedPowerAtTs(address user, uint256 timestamp) public view returns (uint256) {
return _checkpointsBinarySearch(LibKernelStorage.kernelStorage().delegatedPowerHistory[user], timestamp);
}
// same as multiplierAtTs but for the current block timestamp
function multiplierOf(address user) public view returns (uint256) {
return multiplierAtTs(user, block.timestamp);
}
// multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp
// it includes the decay mechanism
function multiplierAtTs(address user, uint256 timestamp) public view returns (uint256) {
LibKernelStorage.Stake memory stake = stakeAtTs(user, timestamp);
return _stakeMultiplier(stake, timestamp);
}
// userLockedUntil returns the timestamp until the user's balance is locked
function userLockedUntil(address user) public view returns (uint256) {
LibKernelStorage.Stake memory c = stakeAtTs(user, block.timestamp);
return c.expiryTimestamp;
}
// userDelegatedTo returns the address to which a user delegated their voting power; address(0) if not delegated
function userDelegatedTo(address user) public view returns (address) {
LibKernelStorage.Stake memory c = stakeAtTs(user, block.timestamp);
return c.delegatedTo;
}
// _checkpointsBinarySearch executes a binary search on a list of checkpoints that's sorted chronologically
// looking for the closest checkpoint that matches the specified timestamp
function _checkpointsBinarySearch(LibKernelStorage.Checkpoint[] storage checkpoints, uint256 timestamp) internal view returns (uint256) {
if (checkpoints.length == 0 || timestamp < checkpoints[0].timestamp) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length - 1;
if (timestamp >= checkpoints[max].timestamp) {
return checkpoints[max].amount;
}
// binary search of the value in the array
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].timestamp <= timestamp) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].amount;
}
// _stakeMultiplier calculates the multiplier for the given stake at the given timestamp
function _stakeMultiplier(LibKernelStorage.Stake memory stake, uint256 timestamp) internal view returns (uint256) {
if (timestamp >= stake.expiryTimestamp) {
return BASE_MULTIPLIER;
}
uint256 diff = stake.expiryTimestamp - timestamp;
if (diff >= MAX_LOCK) {
return BASE_MULTIPLIER.mul(2);
}
return BASE_MULTIPLIER.add(diff.mul(BASE_MULTIPLIER).div(MAX_LOCK));
}
// _updateUserBalance manages an array of checkpoints
// if there's already a checkpoint for the same timestamp, the amount is updated
// otherwise, a new checkpoint is inserted
function _updateUserBalance(LibKernelStorage.Stake[] storage checkpoints, uint256 amount) internal {
if (checkpoints.length == 0) {
checkpoints.push(LibKernelStorage.Stake(block.timestamp, amount, block.timestamp, address(0)));
} else {
LibKernelStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp == block.timestamp) {
old.amount = amount;
} else {
checkpoints.push(LibKernelStorage.Stake(block.timestamp, amount, old.expiryTimestamp, old.delegatedTo));
}
}
}
// _updateUserLock updates the expiry timestamp on the user's stake
// it assumes that if the user already has a balance, which is checked for in the lock function
// then there must be at least 1 checkpoint
function _updateUserLock(LibKernelStorage.Stake[] storage checkpoints, uint256 expiryTimestamp) internal {
LibKernelStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp < block.timestamp) {
checkpoints.push(LibKernelStorage.Stake(block.timestamp, old.amount, expiryTimestamp, old.delegatedTo));
} else {
old.expiryTimestamp = expiryTimestamp;
}
}
// _updateUserDelegatedTo updates the delegateTo property on the user's stake
// it assumes that if the user already has a balance, which is checked for in the delegate function
// then there must be at least 1 checkpoint
function _updateUserDelegatedTo(LibKernelStorage.Stake[] storage checkpoints, address to) internal {
LibKernelStorage.Stake storage old = checkpoints[checkpoints.length - 1];
if (old.timestamp < block.timestamp) {
checkpoints.push(LibKernelStorage.Stake(block.timestamp, old.amount, old.expiryTimestamp, to));
} else {
old.delegatedTo = to;
}
}
// _updateDelegatedPower updates the power delegated TO the user in the checkpoints history
function _updateDelegatedPower(LibKernelStorage.Checkpoint[] storage checkpoints, uint256 amount) internal {
if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].timestamp < block.timestamp) {
checkpoints.push(LibKernelStorage.Checkpoint(block.timestamp, amount));
} else {
LibKernelStorage.Checkpoint storage old = checkpoints[checkpoints.length - 1];
old.amount = amount;
}
}
// _updateLockedLeag stores the new `amount` into the LEAG locked history
function _updateLockedLeag(uint256 amount) internal {
LibKernelStorage.Storage storage ds = LibKernelStorage.kernelStorage();
if (ds.leagStakedHistory.length == 0 || ds.leagStakedHistory[ds.leagStakedHistory.length - 1].timestamp < block.timestamp) {
ds.leagStakedHistory.push(LibKernelStorage.Checkpoint(block.timestamp, amount));
} else {
LibKernelStorage.Checkpoint storage old = ds.leagStakedHistory[ds.leagStakedHistory.length - 1];
old.amount = amount;
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../libraries/LibKernelStorage.sol";
interface IKernel {
// deposit allows a user to add more leag to his staked balance
function deposit(uint256 amount) external;
// withdraw allows a user to withdraw funds if the balance is not locked
function withdraw(uint256 amount) external;
// lock a user's currently staked balance until timestamp & add the bonus to his voting power
function lock(uint256 timestamp) external;
// delegate allows a user to delegate his voting power to another user
function delegate(address to) external;
// stopDelegate allows a user to take back the delegated voting power
function stopDelegate() external;
// lock the balance of a proposal creator until the voting ends; only callable by DAO
function lockCreatorBalance(address user, uint256 timestamp) external;
// balanceOf returns the current LEAG balance of a user (bonus not included)
function balanceOf(address user) external view returns (uint256);
// balanceAtTs returns the amount of LEAG that the user currently staked (bonus NOT included)
function balanceAtTs(address user, uint256 timestamp) external view returns (uint256);
// stakeAtTs returns the Stake object of the user that was valid at `timestamp`
function stakeAtTs(address user, uint256 timestamp) external view returns (LibKernelStorage.Stake memory);
// votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block
function votingPower(address user) external view returns (uint256);
// votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time
function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256);
// leagStaked returns the total raw amount of LEAG staked at the current block
function leagStaked() external view returns (uint256);
// leagStakedAtTs returns the total raw amount of LEAG users have deposited into the contract
// it does not include any bonus
function leagStakedAtTs(uint256 timestamp) external view returns (uint256);
// delegatedPower returns the total voting power that a user received from other users
function delegatedPower(address user) external view returns (uint256);
// delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time
function delegatedPowerAtTs(address user, uint256 timestamp) external view returns (uint256);
// multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp
// it includes the decay mechanism
function multiplierAtTs(address user, uint256 timestamp) external view returns (uint256);
// userLockedUntil returns the timestamp until the user's balance is locked
function userLockedUntil(address user) external view returns (uint256);
// userDidDelegate returns the address to which a user delegated their voting power; address(0) if not delegated
function userDelegatedTo(address user) external view returns (address);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IRewards.sol";
library LibKernelStorage {
bytes32 constant STORAGE_POSITION = keccak256("com.enterdao.kernel.storage");
struct Checkpoint {
uint256 timestamp;
uint256 amount;
}
struct Stake {
uint256 timestamp;
uint256 amount;
uint256 expiryTimestamp;
address delegatedTo;
}
struct Storage {
bool initialized;
// mapping of user address to history of Stake objects
// every user action creates a new object in the history
mapping(address => Stake[]) userStakeHistory;
// array of leag staked Checkpoint
// deposits/withdrawals create a new object in the history (max one per block)
Checkpoint[] leagStakedHistory;
// mapping of user address to history of delegated power
// every delegate/stopDelegate call create a new checkpoint (max one per block)
mapping(address => Checkpoint[]) delegatedPowerHistory;
IERC20 leag;
IRewards rewards;
}
function kernelStorage() internal pure returns (Storage storage ds) {
bytes32 position = STORAGE_POSITION;
assembly {
ds.slot := position
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "./LibDiamondStorage.sol";
library LibOwnership {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
address previousOwner = ds.contractOwner;
require(previousOwner != _newOwner, "Previous owner and new owner must be different");
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = LibDiamondStorage.diamondStorage().contractOwner;
}
function enforceIsContractOwner() view internal {
require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner");
}
modifier onlyOwner {
require(msg.sender == LibDiamondStorage.diamondStorage().contractOwner, "Must be contract owner");
_;
}
}
// 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRewards {
function registerUserAction(address user) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
library LibDiamondStorage {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct Facet {
address facetAddress;
uint16 selectorPosition;
}
struct DiamondStorage {
// function selector => facet address and selector position in selectors array
mapping(bytes4 => Facet) facets;
bytes4[] selectors;
// ERC165
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
}
| _updateDelegatedPower updates the power delegated TO the user in the checkpoints history | function _updateDelegatedPower(LibKernelStorage.Checkpoint[] storage checkpoints, uint256 amount) internal {
if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].timestamp < block.timestamp) {
checkpoints.push(LibKernelStorage.Checkpoint(block.timestamp, amount));
LibKernelStorage.Checkpoint storage old = checkpoints[checkpoints.length - 1];
old.amount = amount;
}
}
| 10,409,962 |
//Address: 0x80616F35Df2ef0CB42280a629761e0350FaFd679
//Contract name: Lotto
//Balance: 0 Ether
//Verification Date: 3/7/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.8;
/**
* Very basic owned/mortal boilerplate. Used for basically everything, for
* security/access control purposes.
*/
contract Owned {
address owner;
modifier onlyOwner {
if (msg.sender != owner) {
throw;
}
_;
}
/**
* Basic constructor. The sender is the owner.
*/
function Owned() {
owner = msg.sender;
}
/**
* Transfers ownership of the contract to a new owner.
* @param newOwner Who gets to inherit this thing.
*/
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
/**
* Shuts down the contract and removes it from the blockchain state.
* Only available to the owner.
*/
function shutdown() onlyOwner {
selfdestruct(owner);
}
/**
* Withdraw all the funds from this contract.
* Only available to the owner.
*/
function withdraw() onlyOwner {
if (!owner.send(this.balance)) {
throw;
}
}
}
/**
* The base interface is what the parent contract expects to be able to use.
* If rules change in the future, and new logic is introduced, it only has to
* implement these methods, wtih the role of the curator being used
* to execute the additional functionality (if any).
*/
contract LotteryGameLogicInterface {
address public currentRound;
function finalizeRound() returns(address);
function isUpgradeAllowed() constant returns(bool);
function transferOwnership(address newOwner);
}
/**
* This contract is pretty generic, as it really only serves to maintain a constant
* address on the blockchain (through upgrades to the game logic), and to maintain
* a history of previous rounds. Note that the rounds will have had ownership
* transferred to the curator (most likely), so there's mostly just here for
* accounting purposes.
*
* A side effect of this is that finalizing a round has to happen from here.
*/
contract Lotto is Owned {
address[] public previousRounds;
LotteryGameLogicInterface public gameLogic;
modifier onlyWhenUpgradeable {
if (!gameLogic.isUpgradeAllowed()) {
throw;
}
_;
}
modifier onlyGameLogic {
if (msg.sender != address(gameLogic)) {
throw;
}
_;
}
/**
* Creates a new lottery contract.
* @param initialGameLogic The starting game logic.
*/
function Lotto(address initialGameLogic) {
gameLogic = LotteryGameLogicInterface(initialGameLogic);
}
/**
* Upgrade the game logic. Only possible to do when the game logic
* has deemed it clear to do so. Hands the old one over to the owner
* for cleanup. Expects the new logic to already be configured.
* @param newLogic New, already-configured game logic.
*/
function setNewGameLogic(address newLogic) onlyOwner onlyWhenUpgradeable {
gameLogic.transferOwnership(owner);
gameLogic = LotteryGameLogicInterface(newLogic);
}
/**
* Returns the current round.
* @return address The current round (when applicable)
*/
function currentRound() constant returns(address) {
return gameLogic.currentRound();
}
/**
* Used to finalize (e.g. pay winners) the current round, then log
* it in the history.
*/
function finalizeRound() onlyOwner {
address roundAddress = gameLogic.finalizeRound();
previousRounds.push(roundAddress);
}
/**
* Tells how many previous rounds exist.
*/
function previousRoundsCount() constant returns(uint) {
return previousRounds.length;
}
// You must think I'm a joke
// I ain't gonna be part of your system
// Man! Pump that garbage in another man's veins
function () {
throw;
}
}
| Shuts down the contract and removes it from the blockchain state. Only available to the owner./ | function shutdown() onlyOwner {
selfdestruct(owner);
}
| 1,766,040 |
pragma solidity ^0.5.15;
interface IERC20 {
function TOTALSUPPLY265() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF676(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER585(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE478(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE401(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM799(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER297(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL288(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER981() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA870() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED51(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER981();
emit OWNERSHIPTRANSFERRED51(address(0), _owner);
}
function OWNER52() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER947() { //inject NONSTANDARD NAMING
require(ISOWNER855(), "Ownable: caller is not the owner");
_;
}
function ISOWNER855() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER981() == _owner;
}
function RENOUNCEOWNERSHIP936() public ONLYOWNER947 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED51(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP177(address newOwner) public ONLYOWNER947 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP636(newOwner);
}
function _TRANSFEROWNERSHIP636(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED51(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY265() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF676(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER585(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(_MSGSENDER981(), recipient, amount);
return true;
}
function ALLOWANCE478(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE401(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, amount);
return true;
}
function TRANSFERFROM799(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(sender, recipient, amount);
_APPROVE768(sender, _MSGSENDER981(), _allowances[sender][_MSGSENDER981()].SUB171(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].ADD125(addedValue));
return true;
}
function DECREASEALLOWANCE775(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].SUB171(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER399(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB171(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD125(amount);
emit TRANSFER297(sender, recipient, amount);
}
function _MINT552(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD125(amount);
_balances[account] = _balances[account].ADD125(amount);
emit TRANSFER297(address(0), account, amount);
}
function _BURN908(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB171(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB171(amount);
emit TRANSFER297(account, address(0), amount);
}
function _APPROVE768(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL288(owner, spender, amount);
}
function _BURNFROM359(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN908(account, amount);
_APPROVE768(account, _MSGSENDER981(), _allowances[account][_MSGSENDER981()].SUB171(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME677() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL955() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS596() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB171(a, b, "SafeMath: subtraction overflow");
}
function SUB171(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL207(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV619(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV619(a, b, "SafeMath: division by zero");
}
function DIV619(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD550(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD550(a, b, "SafeMath: modulo by zero");
}
function MOD550(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT651(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE339(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE156(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER644(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFER585.selector, to, value));
}
function SAFETRANSFERFROM18(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFERFROM799.selector, from, to, value));
}
function SAFEAPPROVE229(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE478(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, value));
}
function SAFEINCREASEALLOWANCE497(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).ADD125(value);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE975(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).SUB171(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN428(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT651(), "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");
}
}
}
interface Controller {
function WITHDRAW158(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF676(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN532(address, uint) external; //inject NONSTANDARD NAMING
function REWARDS630() external view returns (address); //inject NONSTANDARD NAMING
}
// vault1111 111111111111
// abi1111: https://github.com/ystar-foundation/YstarFarming/blob/master/Vault/abi/vault.json
contract Vault {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IERC20 public YFToken; // YF1111
uint public min = 9500;
uint public constant max986 = 10000; //inject NONSTANDARD NAMING
uint public earnLowerlimit; //1111111111111earn
address public governance;
address public controller;
struct Player {
uint256 stake; // 1111
uint256 payout; // 11
uint256 total_out; // 1111111
}
mapping(address => Player) public player_; // (player => data) player data
struct Global {
uint256 total_stake; // 11111
uint256 total_out; // 11111
uint256 earnings_per_share; // 1111
}
mapping(uint256 => Global) public global_; // (global => data) global data
mapping (address => uint256) public deposittime;
uint256 constant internal magnitude720 = 10**40; // 1014011 //inject NONSTANDARD NAMING
address constant public yf82 = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); //inject NONSTANDARD NAMING
string public getName;
constructor (address _token, uint256 _earnLowerlimit) public {
token = IERC20(_token);
getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).NAME677()));
earnLowerlimit = _earnLowerlimit*1e18;
YFToken = IERC20(yf82);
governance = tx.origin;
controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C;
}
function BALANCE265() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this))
.ADD125(Controller(controller).BALANCEOF676(address(token)));
}
function SETMIN245(uint _min) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
min = _min;
}
// 11111111111111111111
function SETGOVERNANCE992(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
// 1111token
function SETTOKEN102(address _token) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
token = IERC20(_token);
}
// 1111111111111111111
function SETCONTROLLER604(address _controller) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function SETEARNLOWERLIMIT476(uint256 _earnLowerlimit) public{ //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
// 11111111111
// 111111111111111111111
function AVAILABLE23() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this)).MUL207(min).DIV619(max986); // balance*min/max 1111111111111111111
}
// 11111Strategy1111111111111 vault->controller->strategy
function EARN532() public { //inject NONSTANDARD NAMING
uint _bal = AVAILABLE23(); // 1111111111111111111111
token.SAFETRANSFER644(controller, _bal); // 1111111
Controller(controller).EARN532(address(token), _bal); // 11111Strategy111111
}
// 11 111111
function DEPOSIT245(uint amount) external { //inject NONSTANDARD NAMING
// 111111111111111111appove1111111111111
token.SAFETRANSFERFROM18(msg.sender, address(this), amount);
// 1111111111
player_[msg.sender].stake = player_[msg.sender].stake.ADD125(amount);
// 11111110
if (global_[0].earnings_per_share != 0) {
player_[msg.sender].payout = player_[msg.sender].payout.ADD125(
global_[0].earnings_per_share.MUL207(amount).SUB171(1).DIV619(magnitude720).ADD125(1) // (((earnings_per_share*amount)-1)/magnitude)+1
);
}
// 1111111111
global_[0].total_stake = global_[0].total_stake.ADD125(amount);
// 111111111111111111111111111111111111111111111
if (token.BALANCEOF676(address(this)) > earnLowerlimit){
EARN532();
}
// 11111111
deposittime[msg.sender] = now;
}
// No rebalance implementation for lower fees and faster swaps
// 11
function WITHDRAW158(uint amount) external { //inject NONSTANDARD NAMING
CLAIM365(); // 111111111111
require(amount <= player_[msg.sender].stake, "!balance");
uint r = amount;
// Check balance
uint b = token.BALANCEOF676(address(this));
if (b < r) { // 11vault111111111111111111111Strategy11111111111
uint _withdraw = r.SUB171(b);
Controller(controller).WITHDRAW158(address(token), _withdraw); // 11
uint _after = token.BALANCEOF676(address(this));
uint _diff = _after.SUB171(b);
if (_diff < _withdraw) { // 111111111111111111111vault111111
r = b.ADD125(_diff);
}
}
// 111111111111111111111
player_[msg.sender].payout = player_[msg.sender].payout.SUB171(
global_[0].earnings_per_share.MUL207(amount).DIV619(magnitude720)
);
// 1111111111111
player_[msg.sender].stake = player_[msg.sender].stake.SUB171(amount);
global_[0].total_stake = global_[0].total_stake.SUB171(amount);
// 1111111111
token.SAFETRANSFER644(msg.sender, r);
}
// Strategy.harvest 111111
function MAKE_PROFIT788(uint256 amount) public { //inject NONSTANDARD NAMING
require(amount > 0, "not 0");
YFToken.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111111110%1111190%1111111
global_[0].earnings_per_share = global_[0].earnings_per_share.ADD125(
amount.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
global_[0].total_out = global_[0].total_out.ADD125(amount);
}
// 11111111
function CAL_OUT246(address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _cal = global_[0].earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 11111111111111111111111111.11111111111harvest1111111111
function CAL_OUT_PENDING918(uint256 _pendingBalance,address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _earnings_per_share = global_[0].earnings_per_share.ADD125(
_pendingBalance.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
uint256 _cal = _earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
_cal = _cal.SUB171(CAL_OUT246(user));
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 111111
function CLAIM365() public { //inject NONSTANDARD NAMING
uint256 out = CAL_OUT246(msg.sender);
player_[msg.sender].payout = global_[0].earnings_per_share.MUL207(player_[msg.sender].stake).DIV619(magnitude720);
player_[msg.sender].total_out = player_[msg.sender].total_out.ADD125(out);
if (out > 0) {
uint256 _depositTime = now - deposittime[msg.sender];
if (_depositTime < 1 days){ // deposit in 24h
uint256 actually_out = _depositTime.MUL207(out).MUL207(1e18).DIV619(1 days).DIV619(1e18);
uint256 to_team = out.SUB171(actually_out);
YFToken.SAFETRANSFER644(Controller(controller).REWARDS630(), to_team);
out = actually_out;
}
YFToken.SAFETRANSFER644(msg.sender, out);
}
}
} | inject NONSTANDARD NAMING | function _BURNFROM359(address account, uint256 amount) internal { | 12,634,621 |
./partial_match/42/0x1F4fC75f9fE0B09d93F63867EF75C9c3A6DC03f0/sources/_contracts/JoysNFTMinning.sol | less than 3days deposit, withdraw will take out 10% | function withdrawPercent(uint256 _from, uint256 _to) public pure returns (uint256) {
if (_from.sub(_to) <= BLOCK_PER_DAY.mul(3)) {
return 90;
}
return 100;
}
| 3,378,055 |
pragma solidity 0.7.6;
import "contracts/protocol/futures/futureWallets/StreamFutureWallet.sol";
/**
* @title Contract for Aave Future Wallet
* @notice Handles the future wallet mechanisms for the Aave platform
* @dev Implement directly the stream future wallet abstraction as it fits the aToken IBT
*/
contract AaveFutureWallet is StreamFutureWallet {
}
pragma solidity 0.7.6;
import "contracts/protocol/futures/futureWallets/FutureWallet.sol";
/**
* @title Strean Future Wallet abstraction
* @notice Abstraction for the future wallets that works with an IBT for which its holder gets the interest directly in its wallet progressively (i.e aTokens)
* @dev Override future wallet abstraction with the particular functioning of stream-based IBT
*/
abstract contract StreamFutureWallet is FutureWallet {
using SafeMathUpgradeable for uint256;
uint256 private scaledTotal;
uint256[] private scaledFutureWallets;
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the admin
*/
function initialize(address _futureAddress, address _adminAddress) public override initializer {
super.initialize(_futureAddress, _adminAddress);
}
/**
* @notice register the yield of an expired period
* @param _amount the amount of yield to be registered
*/
function registerExpiredFuture(uint256 _amount) public override {
require(hasRole(FUTURE_ROLE, msg.sender), "Caller is not allowed to register an expired future");
uint256 currentTotal = ibt.balanceOf(address(this));
if (scaledFutureWallets.length > 1) {
uint256 scaledInput =
IAPWineMaths(IRegistry(IController(future.getControllerAddress()).getRegistryAddress()).getMathsUtils())
.getScaledInput(_amount, scaledTotal, currentTotal);
scaledFutureWallets.push(scaledInput);
scaledTotal = scaledTotal.add(scaledInput);
} else {
scaledFutureWallets.push(_amount);
scaledTotal = scaledTotal.add(_amount);
}
}
/**
* @notice return the yield that could be redeemed by an address for a particular period
* @param _periodIndex the index of the corresponding period
* @param _tokenHolder the FYT holder
* @return the yield that could be redeemed by the token holder for this period
*/
function getRedeemableYield(uint256 _periodIndex, address _tokenHolder) public view override returns (uint256) {
IFutureYieldToken fyt = IFutureYieldToken(future.getFYTofPeriod(_periodIndex));
uint256 senderTokenBalance = fyt.balanceOf(_tokenHolder);
uint256 scaledOutput = (senderTokenBalance.mul(scaledFutureWallets[_periodIndex]));
return
IAPWineMaths(IRegistry(IController(future.getControllerAddress()).getRegistryAddress()).getMathsUtils())
.getActualOutput(scaledOutput, scaledTotal, ibt.balanceOf(address(this)))
.div(fyt.totalSupply());
}
/**
* @notice collect and update the yield balance of the sender
* @param _periodIndex the index of the corresponding period
* @param _userFYT the FYT holder balance
* @param _totalFYT the total FYT supply
* @return the yield claimed
*/
function _updateYieldBalances(
uint256 _periodIndex,
uint256 _userFYT,
uint256 _totalFYT
) internal override returns (uint256) {
uint256 scaledOutput = (_userFYT.mul(scaledFutureWallets[_periodIndex])).div(_totalFYT);
uint256 claimableYield =
IAPWineMaths(IRegistry(IController(future.getControllerAddress()).getRegistryAddress()).getMathsUtils())
.getActualOutput(scaledOutput, scaledTotal, ibt.balanceOf(address(this)));
scaledFutureWallets[_periodIndex] = scaledFutureWallets[_periodIndex].sub(scaledOutput);
scaledTotal = scaledTotal.sub(scaledOutput);
return claimableYield;
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "contracts/interfaces/ERC20.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/IFuture.sol";
import "contracts/interfaces/apwine/IController.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
import "contracts/interfaces/apwine/utils/IAPWineMath.sol";
/**
* @title Future Wallet abstraction
* @notice Main abstraction for the future wallets contract
* @dev The future wallets stores the yield after each expiration of the future period
*/
abstract contract FutureWallet is Initializable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant FUTURE_ROLE = keccak256("FUTURE_ROLE");
IFuture public future;
ERC20 public ibt;
bool public WITHRAWALS_PAUSED;
event YieldRedeemed(address _user, uint256 _periodIndex);
event WithdrawalsPaused();
event WithdrawalsResumed();
modifier withdrawalsEnabled() {
require(!WITHRAWALS_PAUSED, "withdrawals are disabled");
_;
}
/**
* @notice Intializer
* @param _futureAddress the address of the corresponding future
* @param _adminAddress the address of the admin
*/
function initialize(address _futureAddress, address _adminAddress) public virtual initializer {
future = IFuture(_futureAddress);
ibt = ERC20(future.getIBTAddress());
_setupRole(DEFAULT_ADMIN_ROLE, _adminAddress);
_setupRole(ADMIN_ROLE, _adminAddress);
_setupRole(FUTURE_ROLE, _futureAddress);
}
/**
* @notice register the yield of an expired period
* @param _amount the amount of yield to be registered
* @dev the caller need to transfer the yield after calling this function
*/
function registerExpiredFuture(uint256 _amount) public virtual;
/**
* @notice redeem the yield of the underlying yield of the FYT held by the sender
* @param _periodIndex the index of the period to redeem the yield from
*/
function redeemYield(uint256 _periodIndex) public virtual nonReentrant withdrawalsEnabled {
require(_periodIndex < future.getNextPeriodIndex() - 1, "Invalid period index");
IFutureYieldToken fyt = IFutureYieldToken(future.getFYTofPeriod(_periodIndex));
uint256 senderTokenBalance = fyt.balanceOf(msg.sender);
require(senderTokenBalance > 0, "FYT sender balance should not be null");
uint256 claimableYield = _updateYieldBalances(_periodIndex, senderTokenBalance, fyt.totalSupply());
fyt.burnFrom(msg.sender, senderTokenBalance);
ibt.transfer(msg.sender, claimableYield);
emit YieldRedeemed(msg.sender, _periodIndex);
}
/**
* @notice return the yield that could be redeemed by an address for a particular period
* @param _periodIndex the index of the corresponding period
* @param _tokenHolder the FYT holder
* @return the yield that could be redeemed by the token holder for this period
*/
function getRedeemableYield(uint256 _periodIndex, address _tokenHolder) public view virtual returns (uint256);
/**
* @notice collect and update the yield balance of the sender
* @param _periodIndex the index of the corresponding period
* @param _userFYT the FYT holder balance
* @param _totalFYT the total FYT supply
* @return the yield that could be redeemed by the token holder for this period
*/
function _updateYieldBalances(
uint256 _periodIndex,
uint256 _userFYT,
uint256 _totalFYT
) internal virtual returns (uint256);
/**
* @notice getter for the address of the future corresponding to this future wallet
* @return the address of the future
*/
function getFutureAddress() public view virtual returns (address) {
return address(future);
}
/**
* @notice getter for the address of the IBT corresponding to this future wallet
* @return the address of the IBT
*/
function getIBTAddress() public view virtual returns (address) {
return address(ibt);
}
/* Admin functions */
/**
* @notice Pause withdrawals
*/
function pauseWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to pause withdrawals");
WITHRAWALS_PAUSED = true;
emit WithdrawalsPaused();
}
/**
* @notice Resume withdrawals
*/
function resumeWithdrawals() public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume withdrawals");
WITHRAWALS_PAUSED = false;
emit WithdrawalsResumed();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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() external returns (uint8);
/**
* @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) external returns (bool);
/**
* @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) external returns (bool);
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @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`.
*/
function burnFrom(address account, uint256 amount) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
pragma solidity 0.7.6;
interface IFuture {
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
/**
* @notice Getter for the PAUSE future parameter
* @return true if new periods are paused, false otherwise
*/
function PAUSED() external view returns (bool);
/**
* @notice Getter for the PERIOD future parameter
* @return returns the period duration of the future
*/
function PERIOD_DURATION() external view returns (uint256);
/**
* @notice Getter for the PLATFORM_NAME future parameter
* @return returns the platform of the future
*/
function PLATFORM_NAME() external view returns (uint256);
/**
* @notice Initializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) external;
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) external;
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) external;
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) external;
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) external;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) external;
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) external;
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user the user address
* @param _amount amount of funds to unlocked
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) external;
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) external;
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() external;
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) external view returns (bool);
/**
* @notice Check if a user has unclaimed apwIBT
* @param _user the user to check
* @return true if the user can claim some apwIBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) external view returns (bool);
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) external view returns (uint256);
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) external view returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user the user to check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user user to check the check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) external view returns (uint256);
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() external view returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() external view returns (address);
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() external view returns (address);
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() external view returns (address);
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() external view returns (address);
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) external view returns (address);
/* Admin functions*/
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() external;
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() external;
}
pragma solidity 0.7.6;
interface IController {
/* Getters */
function STARTING_DELAY() external view returns (uint256);
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin) external;
/* Future Settings Setters */
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) external;
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the duration of a period
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) external;
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) external;
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) external;
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) external;
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) external;
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) external;
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory);
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address);
/**
* @notice Getter for the symbol of the apwIBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the apwIBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the apwIBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) external view returns (string memory);
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the periods duration
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for beginning timestamp of the next period for the futures with a defined periods duration
* @param _periodDuration the periods duration
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the periods duration
* @return the factor of claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) external view returns (uint256);
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of futures duration
*/
function getDurations() external view returns (uint256[] memory);
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) external;
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) external;
/**
* @notice Start all the futures that have a defined periods duration to synchronize them
* @param _periodDuration the periods duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) external;
/**
* @notice Getter for the futures by periods duration
* @param _periodDuration the periods duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) external view returns (address[] memory);
/**
* @notice Register the sender to the corresponding future
* @param _user the address of the user
* @param _futureAddress the addresses of the futures to claim the fyts from
*/
function claimSelectedYield(address _user, address[] memory _futureAddress) external;
function getRoleMember(bytes32 role, uint256 index) external view returns (address); // OZ ACL getter
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) external;
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
pragma solidity 0.7.6;
interface IAPWineMaths {
/**
* @notice scale an input
* @param _actualValue the original value of the input
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getScaledInput(
uint256 _actualValue,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
/**
* @notice scale back a value to the output
* @param _scaledOutput the current scaled output
* @param _initialSum the scaled value of the sum of the inputs
* @param _actualSum the current value of the sum of the inputs
*/
function getActualOutput(
uint256 _scaledOutput,
uint256 _initialSum,
uint256 _actualSum
) external pure returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | Intializer _futureAddress the address of the corresponding future _adminAddress the address of the admin/ | function initialize(address _futureAddress, address _adminAddress) public override initializer {
super.initialize(_futureAddress, _adminAddress);
}
| 314,505 |
./full_match/1/0xD8262F646Cd001430cea2eEcDfe3536547A1E95C/sources/NieuxCollective.sol | Sets the default royalty for the contract receiver address to receive the royalty feeNumerator the royalty fee numerator/ | function setDefaultRoyalty(
address receiver,
uint96 feeNumerator
) public payable onlyOwner {
_receiver = receiver;
_setDefaultRoyalty(_receiver, feeNumerator);
}
| 3,193,387 |
./partial_match/1/0x13F56D5d6193EE95F094fe9448Cbbd783dF95498/sources/src/ERC721SeaDrop.sol | Equivalent to `safeTransferFrom(from, to, tokenId, '')`./ | function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId);
}
| 3,587,469 |
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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/math/SafeMath.sol
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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
pragma solidity ^0.4.24;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal 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(_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 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/ERC20.sol
pragma solidity ^0.4.24;
/**
* @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
pragma solidity ^0.4.24;
/**
* @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 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(_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 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,
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;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @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 relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/base/MintableToken.sol
pragma solidity ^0.4.24;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* 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);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @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
)
public
hasMintPermission
canMint
returns (bool)
{
return _mint(_to, _amount);
}
/**
* @dev Internal 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
)
internal
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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Destructible.sol
pragma solidity ^0.4.24;
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.24;
/**
* @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() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
pragma solidity ^0.4.24;
/**
* @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/DetailedERC20.sol
pragma solidity ^0.4.24;
/**
* @title DetailedERC20 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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/ECRecovery.sol
pragma solidity ^0.4.24;
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param _sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 _hash, bytes _sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(_hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 _hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
);
}
}
// File: contracts/SilverToken.sol
pragma solidity ^0.4.24;
interface ASilverDollar {
function purchaseWithSilverToken(address, uint256) external returns(bool);
}
contract SilverToken is Destructible, Pausable, MintableToken, BurnableToken, DetailedERC20("Silvertoken", "SLVT", 8), Whitelist {
using SafeMath for uint256;
using ECRecovery for bytes32;
uint256 public transferFee = 10;//1%
uint256 public transferDiscountFee = 8;//0.8%
uint256 public redemptionFee = 40;//4%
uint256 public convertFee = 10;//1%
address public feeReturnAddress = 0xE34f13B2dadC938f44eCbC38A8dBe94B8bdB2109;
uint256 public transferFreeAmount;
uint256 public transferDiscountAmount;
address public silverDollarAddress;
address public SLVTReserve = 0x900122447a2Eaeb1655C99A91E20f506D509711B;
bool public canPurchase = true;
bool public canConvert = true;
// Internal features
uint256 internal multiplier;
uint256 internal percentage = 1000;
//ce4385affa8ad2cbec45b1660c6f6afcb691bf0a7a73ebda096ee1dfb670fe6f
event TokenRedeemed(address from, uint256 amount);
//3ceffd410054fdaed44f598ff5c1fb450658778e2241892da4aa646979dee617
event TokenPurchased(address addr, uint256 amount, uint256 tokens);
//5a56a31cc0c9ebf5d0626c5189b951fe367d953afc1824a8bb82bf168713cc52
event FeeApplied(string name, address addr, uint256 amount);
event Converted(address indexed sender, uint256 amountSLVT, uint256 amountSLVD, uint256 amountFee);
modifier purchasable() {
require(canPurchase == true, "can't purchase");
_;
}
modifier onlySilverDollar() {
require(msg.sender == silverDollarAddress, "not silverDollar");
_;
}
modifier isConvertible() {
require(canConvert == true, "SLVT conversion disabled");
_;
}
constructor () public {
multiplier = 10 ** uint256(decimals);
transferFreeAmount = 2 * multiplier;
transferDiscountAmount = 500 * multiplier;
owner = msg.sender;
super.mint(msg.sender, 1 * 1000 * 1000 * multiplier);
}
// Settings begin
function setTransferFreeAmount(uint256 value) public onlyOwner { transferFreeAmount = value; }
function setTransferDiscountAmount(uint256 value) public onlyOwner { transferDiscountAmount = value; }
function setRedemptionFee(uint256 value) public onlyOwner { redemptionFee = value; }
function setFeeReturnAddress(address value) public onlyOwner { feeReturnAddress = value; }
function setCanPurchase(bool value) public onlyOwner { canPurchase = value; }
function setSilverDollarAddress(address value) public onlyOwner { silverDollarAddress = value; }
function setCanConvert(bool value) public onlyOwner { canConvert = value; }
function setConvertFee(uint256 value) public onlyOwner { convertFee = value; }
function increaseTotalSupply(uint256 value) public onlyOwner returns (uint256) {
super.mint(owner, value);
return totalSupply_;
}
// Settings end
// ERC20 re-implementation methods begin
function transfer(address to, uint256 amount) public whenNotPaused returns (bool) {
uint256 feesPaid = payFees(address(0), to, amount);
require(super.transfer(to, amount.sub(feesPaid)), "failed transfer");
return true;
}
function transferFrom(address from, address to, uint256 amount) public whenNotPaused returns (bool) {
uint256 feesPaid = payFees(from, to, amount);
require(super.transferFrom(from, to, amount.sub(feesPaid)), "failed transferFrom");
return true;
}
// ERC20 re-implementation methods end
// Silvertoken methods end
function payFees(address from, address to, uint256 amount) private returns (uint256 fees) {
if (msg.sender == owner || hasRole(from, ROLE_WHITELISTED) || hasRole(msg.sender, ROLE_WHITELISTED) || hasRole(to, ROLE_WHITELISTED))
return 0;
fees = getTransferFee(amount);
if (from == address(0)) {
require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed");
}
else {
require(super.transferFrom(from, feeReturnAddress, fees), "transferFrom fee payment failed");
}
emit FeeApplied("Transfer", to, fees);
}
function getTransferFee(uint256 amount) internal view returns(uint256) {
if (transferFreeAmount > 0 && amount <= transferFreeAmount) return 0;
if (transferDiscountAmount > 0 && amount >= transferDiscountAmount) return amount.mul(transferDiscountFee).div(percentage);
return amount.mul(transferFee).div(percentage);
}
function transferTokens(address from, address to, uint256 amount) internal returns (bool) {
require(balances[from] >= amount, "balance insufficient");
balances[from] = balances[from].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(from, to, amount);
return true;
}
function purchase(uint256 tokens, uint256 fee, uint256 timestamp, bytes signature) public payable purchasable whenNotPaused {
require(
isSignatureValid(
msg.sender, msg.value, tokens, fee, timestamp, signature
),
"invalid signature"
);
require(tokens > 0, "invalid number of tokens");
emit TokenPurchased(msg.sender, msg.value, tokens);
transferTokens(owner, msg.sender, tokens);
feeReturnAddress.transfer(msg.value);
if (fee > 0) {
emit FeeApplied("Purchase", msg.sender, fee);
}
}
function purchasedSilverDollar(uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) {
require(super._mint(SLVTReserve, amount), "minting of slvT failed");
return true;
}
function purchaseWithSilverDollar(address to, uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) {
require(transferTokens(SLVTReserve, to, amount), "failed transfer of slvT from reserve");
return true;
}
function redeem(uint256 tokens) public whenNotPaused {
require(tokens > 0, "amount of tokens redeemed must be > 0");
uint256 fee = tokens.mul(redemptionFee).div(percentage);
_burn(msg.sender, tokens.sub(fee));
if (fee > 0) {
require(super.transfer(feeReturnAddress, fee), "token transfer failed");
emit FeeApplied("Redeem", msg.sender, fee);
}
emit TokenRedeemed(msg.sender, tokens);
}
function isSignatureValid(
address sender, uint256 amount, uint256 tokens,
uint256 fee, uint256 timestamp, bytes signature
) public view returns (bool)
{
if (block.timestamp > timestamp + 10 minutes) return false;
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
sender,
amount,
tokens,
fee,
timestamp
)
);
return hash.toEthSignedMessageHash().recover(signature) == owner;
}
function isConvertSignatureValid(
address sender, uint256 amountSLVT, uint256 amountSLVD,
uint256 timestamp, bytes signature
) public view returns (bool)
{
if (block.timestamp > timestamp + 10 minutes) return false;
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
sender,
amountSLVT,
amountSLVD,
timestamp
)
);
return hash.toEthSignedMessageHash().recover(signature) == owner;
}
function convertToSLVD(
uint256 amountSLVT, uint256 amountSLVD,
uint256 timestamp, bytes signature
) public isConvertible whenNotPaused returns (bool) {
require(
isConvertSignatureValid(
msg.sender, amountSLVT,
amountSLVD, timestamp, signature
),
"convert failed, invalid signature"
);
uint256 fees = amountSLVT.mul(convertFee).div(percentage);
if (whitelist(msg.sender) && Whitelist(silverDollarAddress).whitelist(msg.sender))
fees = 0;
super.transfer(SLVTReserve, amountSLVT.sub(fees));
require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed");
require(
ASilverDollar(silverDollarAddress).purchaseWithSilverToken(msg.sender, amountSLVD),
"failed purchase of silverdollar with silvertoken"
);
emit Converted(msg.sender, amountSLVD, amountSLVD, fees);
return true;
}
} | Internal Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./ | function _mint(
address _to,
uint256 _amount
)
internal
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
| 969,385 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../enums/CrowdfundingStatus.sol";
interface ITimeBasedCrowdfunding {
//try start the start the ICO. If ICO already started returns in PROGRESS status
function start() external returns (CrowdfundingStatus);
//end the ICO
function end() external returns (CrowdfundingStatus);
}
| try start the start the ICO. If ICO already started returns in PROGRESS statusend the ICO | interface ITimeBasedCrowdfunding {
function start() external returns (CrowdfundingStatus);
function end() external returns (CrowdfundingStatus);
pragma solidity ^0.8.0;
}
| 2,541,423 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract AccessManager is AccessControlUpgradeable {
// clientManager
bytes32 public constant CREATE_CLIENT_ROLE =
keccak256("CREATE_CLIENT_ROLE");
bytes32 public constant UPGRADE_CLIENT_ROLE =
keccak256("UPGRADE_CLIENT_ROLE");
bytes32 public constant REGISTER_RELAYER_ROLE =
keccak256("REGISTER_RELAYER_ROLE");
// routing
bytes32 public constant SET_ROUTING_RULES_ROLE =
keccak256("SET_ROUTING_RULES_ROLE");
bytes32 public constant ADD_ROUTING_ROLE = keccak256("ADD_ROUTING_ROLE");
// transfer
bytes32 public constant ON_RECVPACKET_ROLE =
keccak256("ON_RECVPACKET_ROLE");
bytes32 public constant ON_ACKNOWLEDGEMENT_PACKET_ROLE =
keccak256("ON_ACKNOWLEDGEMENT_PACKET_ROLE");
// multi-signature contract address
address public multiSignWallet;
// check if caller is multi-signature contract address
modifier onlyMultiSignWallet() {
require(
msg.sender == multiSignWallet,
"caller not multi-signature contract address"
);
_;
}
function initialize(address _multiSignWallet) public initializer {
multiSignWallet = _multiSignWallet;
_setupRole(DEFAULT_ADMIN_ROLE, multiSignWallet);
// clientManager
_setupRole(CREATE_CLIENT_ROLE, _multiSignWallet);
_setupRole(UPGRADE_CLIENT_ROLE, _multiSignWallet);
_setupRole(REGISTER_RELAYER_ROLE, _multiSignWallet);
// routing
_setupRole(SET_ROUTING_RULES_ROLE, _multiSignWallet);
_setupRole(ADD_ROUTING_ROLE, _multiSignWallet);
// transfer
_setupRole(ON_RECVPACKET_ROLE, _multiSignWallet);
_setupRole(ON_ACKNOWLEDGEMENT_PACKET_ROLE, _multiSignWallet);
}
/**
* @notice dynamically add roles through multi-signature contract addresses
* @param role role
* @param account the address corresponding to the role
*/
function addRole(bytes32 role, address account)
external
onlyMultiSignWallet
{
_setupRole(role, account);
}
/**
* @notice authorize a designated role to an address through a multi-signature contract address
* @param role role
* @param account authorized address
*/
function grantRole(bytes32 role, address account)
public
override
onlyMultiSignWallet
{
super.grantRole(role, account);
}
/**
* @notice cancel the authorization to assign a role to a certain address through the multi-signature contract address
* @param role role
* @param account deauthorized address
*/
function revokeRole(bytes32 role, address account)
public
override
onlyMultiSignWallet
{
super.revokeRole(role, account);
}
/**
* @notice dynamically add roles through multi-signature contract addresses
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchAddRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchAdd: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
_setupRole(roles[i], accounts[i]);
}
}
/**
* @notice volume authorization, roles and addresses need to be one-to-one correspondence
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchGrantRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchGrant: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
super.grantRole(roles[i], accounts[i]);
}
}
/**
* @notice batch deauthorization, roles and addresses need to be one-to-one correspondence
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchRevokeRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchRevoke: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
super.revokeRole(roles[i], accounts[i]);
}
}
}
| cancel the authorization to assign a role to a certain address through the multi-signature contract address role role account deauthorized address/ | function revokeRole(bytes32 role, address account)
public
override
onlyMultiSignWallet
{
super.revokeRole(role, account);
}
| 908,782 |
pragma solidity 0.5.16;
import "./Governable.sol";
contract Controllable is Governable {
constructor(address _storage) public Governable(_storage) {}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance() {
require(
(store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance"
);
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
pragma solidity 0.5.16;
import "./Storage.sol";
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns (bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function forceUnleashed(address _vault) external;
function hasVault(address _vault) external returns (bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(
address _strategy,
address _token,
uint256 amount
) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
}
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(
address recipient,
address token,
uint256 amount
) external;
function forceUnleashed() external;
function depositArbCheck() external view returns (bool);
}
pragma solidity 0.5.16;
interface IVault {
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator)
external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
// force unleash should be callable only by the controller (by the force unleasher) or by governance
function forceUnleashed() external;
function rebalance() external;
}
pragma solidity 0.5.16;
import "./OneInchStrategy_ETH_X.sol";
/**
* This strategy is for the ETH/DAI LP token on 1inch
*/
contract OneInchStrategy_ETH_DAI is OneInchStrategy_ETH_X {
address public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
constructor(address _storage, address _vault)
public
OneInchStrategy_ETH_X(
_storage,
_vault,
address(0x7566126f2fD0f2Dddae01Bb8A6EA49b760383D5A), // underlying
address(0xCa6E3EBF4Ac8c3E84BCCDF5Cd89aece74D69F2a7), // pool
address(0x0EF1B8a0E726Fc3948E15b23993015eB1627f210) // oneInchEthLP
)
{
require(token1 == dai, "token1 mismatch");
}
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interface/IMooniswap.sol";
import "./interface/IFarmingRewards.sol";
import "../../uniswap/interfaces/IUniswapV2Router02.sol";
import "../../interfaces/IStrategy.sol";
import "../../interfaces/IVault.sol";
import "../../weth/Weth9.sol";
import "../StrategyBase.sol";
/**
* This strategy is for ETH / X 1inch LP tokens
* ETH must be token0, and the other token is denoted X
*/
contract OneInchStrategy_ETH_X is StrategyBase {
// 1inch / ETH reward pool: 0x9070832CF729A5150BB26825c2927e7D343EabD9
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Liquidating(address token, uint256 amount);
event ProfitsNotCollected(address token);
address public pool;
address public oneInch =
address(0x111111111117dC0aa78b770fA6A738034120C302);
address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public oneInchCaller =
address(0xe069CB01D06bA617bCDf789bf2ff0D5E5ca20C71);
uint256 maxUint = uint256(~0);
address public oneInchEthLP;
address[] public uniswap_WETH2Token1;
// token0 is ETH
address public token1;
uint256 slippageNumerator = 9;
uint256 slippageDenominator = 10;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
// minimum 1inch amount to be liquidation
uint256 public sellFloorOneInch = 1e17;
constructor(
address _storage,
address _vault,
address _underlying,
address _pool,
address _oneInchEthLP
) public StrategyBase(_storage, _underlying, _vault, weth, address(0)) {
require(
IVault(_vault).underlying() == _underlying,
"vault does not support the required LP token"
);
token1 = IMooniswap(_underlying).token1();
pool = _pool;
require(token1 != address(0), "token1 must be non-zero");
require(
IMooniswap(_underlying).token0() == address(0),
"token0 must be 0x0 (Ether)"
);
oneInchEthLP = _oneInchEthLP;
uniswap_WETH2Token1 = [weth, token1];
// making 1inch reward token salvagable to be able to
// liquidate externally
unsalvagableTokens[oneInch] = false;
unsalvagableTokens[token1] = true;
}
function depositArbCheck() public view returns (bool) {
return true;
}
/**
* Salvages a token. We should not be able to salvage underlying.
*/
function salvage(
address recipient,
address token,
uint256 amount
) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(
!unsalvagableTokens[token],
"token is defined as not salvageable"
);
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Withdraws underlying from the investment pool that mints crops.
*/
function withdrawUnderlyingFromPool(uint256 amount) internal {
IFarmingRewards(pool).withdraw(
Math.min(IFarmingRewards(pool).balanceOf(address(this)), amount)
);
}
/**
* Withdraws the underlying tokens to the pool in the specified amount.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
withdrawUnderlyingFromPool(amountUnderlying);
require(
IERC20(underlying).balanceOf(address(this)) >= amountUnderlying,
"insufficient balance for the withdrawal"
);
IERC20(underlying).safeTransfer(vault, amountUnderlying);
}
/**
* Withdraws all the underlying tokens to the pool.
*/
function withdrawAllToVault() external restricted {
claimAndLiquidate();
withdrawUnderlyingFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
/**
* Invests all the underlying into the pool that mints crops (1inch)
*/
function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
IFarmingRewards(pool).stake(underlyingBalance);
}
}
function() external payable {}
/**
* Claims the 1Inch crop, converts it accordingly
*/
function claimAndLiquidate() internal {
if (!sell) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected(oneInch);
return;
}
IFarmingRewards(pool).getReward();
uint256 oneInchBalance = IERC20(oneInch).balanceOf(address(this));
if (oneInchBalance < sellFloorOneInch) {
emit ProfitsNotCollected(oneInch);
return;
}
// converting the reward token (1inch) into Ether
uint256 amountOutMin = 1;
IERC20(oneInch).safeApprove(oneInchEthLP, 0);
IERC20(oneInch).safeApprove(oneInchEthLP, oneInchBalance);
IMooniswap(oneInchEthLP).swap(
oneInch,
address(0),
oneInchBalance,
amountOutMin,
address(0)
);
// convert the received Ether into wrapped Ether
WETH9(weth).deposit.value(address(this).balance)();
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
if (wethBalance == 0) {
emit ProfitsNotCollected(weth);
return;
}
// share 30% of the wrapped Ether as a profit sharing reward
notifyProfitInRewardToken(wethBalance);
uint256 remainingWethBalance = IERC20(weth).balanceOf(address(this));
IERC20(weth).safeApprove(uni, 0);
IERC20(weth).safeApprove(uni, remainingWethBalance.div(2));
// with the remaining, half would be converted into the second token
IUniswapV2Router02(uni).swapExactTokensForTokens(
remainingWethBalance.div(2),
amountOutMin,
uniswap_WETH2Token1,
address(this),
block.timestamp
);
uint256 token1Amount = IERC20(token1).balanceOf(address(this));
// and the other half - unwrapped
remainingWethBalance = IERC20(weth).balanceOf(address(this));
IERC20(weth).safeApprove(weth, 0);
IERC20(weth).safeApprove(weth, remainingWethBalance);
WETH9(weth).withdraw(remainingWethBalance);
uint256 remainingEthBalance = address(this).balance;
IERC20(token1).safeApprove(underlying, 0);
IERC20(token1).safeApprove(underlying, token1Amount);
// adding liquidity: ETH + token1
IMooniswap(underlying).deposit.value(remainingEthBalance)(
[remainingEthBalance, token1Amount],
[
remainingEthBalance.mul(slippageNumerator).div(
slippageDenominator
),
token1Amount.mul(slippageNumerator).div(slippageDenominator)
]
);
}
/**
* Claims and liquidates 1inch into underlying, and then invests all underlying.
*/
function forceUnleashed() public restricted {
claimAndLiquidate();
investAllUnderlying();
}
/**
* Investing all underlying.
*/
function investedUnderlyingBalance() public view returns (uint256) {
return
IFarmingRewards(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Can completely disable claiming 1inch rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of 1inch needed to trigger a sale.
*/
function setSellFloorAndSlippages(
uint256 _sellFloorOneInch,
uint256 _slippageNumerator,
uint256 _slippageDenominator
) public onlyGovernance {
sellFloorOneInch = _sellFloorOneInch;
slippageNumerator = _slippageNumerator;
slippageDenominator = _slippageDenominator;
}
}
pragma solidity 0.5.16;
interface IFarmingRewards {
function balanceOf(address account) external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function exit() external;
function getReward() external;
}
pragma solidity 0.5.16;
contract IMooniswap {
function token0() external view returns (address);
function token1() external view returns (address);
function getTokens() external view returns (address[] memory tokens);
function tokens(uint256 i) external view returns (address);
function deposit(
uint256[2] calldata maxAmounts,
uint256[2] calldata minAmounts
)
external
payable
returns (uint256 fairSupply, uint256[2] memory receivedAmounts);
function swap(
address src,
address dst,
uint256 amount,
uint256 minReturn,
address referral
) external payable returns (uint256 result);
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IController.sol";
import "../Controllable.sol";
contract RewardTokenProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public rewardToken;
constructor(address _storage, address _rewardToken)
public
Controllable(_storage)
{
rewardToken = _rewardToken;
profitSharingNumerator = 0;
profitSharingDenominator = 100;
require(
profitSharingNumerator < profitSharingDenominator,
"invalid profit share"
);
}
event ProfitLogInReward(
uint256 profitAmount,
uint256 feeAmount,
uint256 timestamp
);
function notifyProfitInRewardToken(uint256 _rewardBalance) internal {
if (_rewardBalance > 0 && profitSharingNumerator > 0) {
uint256 feeAmount =
_rewardBalance.mul(profitSharingNumerator).div(
profitSharingDenominator
);
emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(controller(), 0);
IERC20(rewardToken).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(rewardToken, feeAmount);
} else {
emit ProfitLogInReward(0, 0, block.timestamp);
}
}
function setProfitSharingNumerator(uint256 _profitSharingNumerator)
external
onlyGovernance
{
profitSharingNumerator = _profitSharingNumerator;
}
}
pragma solidity 0.5.16;
import "./RewardTokenProfitNotifier.sol";
import "../interfaces/IStrategy.sol";
contract StrategyBase is IStrategy, RewardTokenProfitNotifier {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitsNotCollected(address);
event Liquidating(address, uint256);
address public underlying;
address public vault;
mapping(address => bool) public unsalvagableTokens;
address public uniswapRouterV2;
modifier restricted() {
require(
msg.sender == vault ||
msg.sender == address(controller()) ||
msg.sender == address(governance()),
"The sender has to be the controller or vault or governance"
);
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardToken,
address _uniswap
) public RewardTokenProfitNotifier(_storage, _rewardToken) {
underlying = _underlying;
vault = _vault;
unsalvagableTokens[_rewardToken] = true;
unsalvagableTokens[_underlying] = true;
uniswapRouterV2 = _uniswap;
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
pragma solidity >=0.5.0;
import "./IUniswapV2Router01.sol";
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// based on https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
/**
*Submitted for verification at Etherscan.io on 2017-12-12
*/
// Copyright (C) 2015, 2016, 2017 Dapphub
// 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/>.
pragma solidity 0.5.16;
contract WETH9 {
function balanceOf(address target) public view returns (uint256);
function deposit() public payable;
function withdraw(uint256 wad) public;
function totalSupply() public view returns (uint256);
function approve(address guy, uint256 wad) public returns (bool);
function transfer(address dst, uint256 wad) public returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool);
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
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);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 "./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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | Withdraws all the underlying tokens to the pool./ | function withdrawAllToVault() external restricted {
claimAndLiquidate();
withdrawUnderlyingFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
| 11,727,816 |
./full_match/43114/0xE487a3780D56F2ECD142201907dF16350bb09946/sources/DssProxyActions.sol | on first dent, clear as much Ash as possible | function dent(uint id, uint lot, uint bid) external note {
require(live == 1, "Flopper/not-live");
require(bids[id].guy != address(0), "Flopper/guy-not-set");
require(bids[id].tic > now || bids[id].tic == 0, "Flopper/already-finished-tic");
require(bids[id].end > now, "Flopper/already-finished-end");
require(bid == bids[id].bid, "Flopper/not-matching-bid");
require(lot < bids[id].lot, "Flopper/lot-not-lower");
require(mul(beg, lot) <= mul(bids[id].lot, ONE), "Flopper/insufficient-decrease");
if (msg.sender != bids[id].guy) {
vat.move(msg.sender, bids[id].guy, bid);
if (bids[id].tic == 0) {
uint Ash = Vow(bids[id].guy).Ash();
Vow(bids[id].guy).kiss(min(bid, Ash));
}
bids[id].guy = msg.sender;
}
bids[id].lot = lot;
bids[id].tic = add(uint48(now), ttl);
}
| 4,579,539 |
/*
Copyright 2017 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2017 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance.
/// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]>
contract TokenTransferProxy is Ownable {
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
modifier targetAuthorized(address target) {
require(authorized[target]);
_;
}
modifier targetNotAuthorized(address target) {
require(!authorized[target]);
_;
}
mapping (address => bool) public authorized;
address[] public authorities;
event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
event LogAuthorizedAddressRemoved(address indexed target, address indexed caller);
function TokenTransferProxy() Ownable() {
// This is here for our verification code only
}
/*
* Public functions
*/
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
public
onlyOwner
targetNotAuthorized(target)
{
authorized[target] = true;
authorities.push(target);
LogAuthorizedAddressAdded(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
public
onlyOwner
targetAuthorized(target)
{
delete authorized[target];
for (uint i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
authorities[i] = authorities[authorities.length - 1];
authorities.length -= 1;
break;
}
}
LogAuthorizedAddressRemoved(target, msg.sender);
}
/// @dev Calls into ERC20 Token contract, invoking transferFrom.
/// @param token Address of token to transfer.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param value Amount of token to transfer.
/// @return Success of transfer.
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyAuthorized
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
/*
* Public constant functions
*/
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
public
constant
returns (address[])
{
return authorities;
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal constant returns (uint256) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal constant returns (uint256) {
uint c = a / b;
return c;
}
function safeSub(uint a, uint b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal constant returns (uint256) {
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;
}
}
contract Whitelist is Ownable {
mapping (address => uint128) whitelist;
event Whitelisted(address who, uint128 nonce);
function Whitelist() Ownable() {
// This is here for our verification code only
}
function setWhitelisting(address who, uint128 nonce) internal {
whitelist[who] = nonce;
Whitelisted(who, nonce);
}
function whitelistUser(address who, uint128 nonce) external onlyOwner {
setWhitelisting(who, nonce);
}
function whitelistMe(uint128 nonce, uint8 v, bytes32 r, bytes32 s) external {
bytes32 hash = keccak256(msg.sender, nonce);
require(ecrecover(hash, v, r, s) == owner);
require(whitelist[msg.sender] == 0);
setWhitelisting(msg.sender, nonce);
}
function isWhitelisted(address who) external view returns(bool) {
return whitelist[who] > 0;
}
}
/// @title Exchange - Facilitates exchange of ERC20 tokens.
/// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]>
contract Exchange is SafeMath, Ownable {
// Error Codes
enum Errors {
ORDER_EXPIRED, // Order has already expired
ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled
ROUNDING_ERROR_TOO_LARGE, // Rounding error too large
INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer
}
string constant public VERSION = "1.0.0";
uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas
address public ZRX_TOKEN_CONTRACT;
address public TOKEN_TRANSFER_PROXY_CONTRACT;
Whitelist public whitelist; // Maybe we need to make this mutable?
// Mappings of orderHash => amounts of takerTokenAmount filled or cancelled.
mapping (bytes32 => uint) public filled;
mapping (bytes32 => uint) public cancelled;
event LogFill(
address indexed maker,
address taker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint filledMakerTokenAmount,
uint filledTakerTokenAmount,
uint paidMakerFee,
uint paidTakerFee,
bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair
bytes32 orderHash
);
event LogCancel(
address indexed maker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint cancelledMakerTokenAmount,
uint cancelledTakerTokenAmount,
bytes32 indexed tokens,
bytes32 orderHash
);
event LogError(uint8 indexed errorId, bytes32 indexed orderHash);
struct Order {
address maker;
address taker;
address makerToken;
address takerToken;
address feeRecipient;
uint makerTokenAmount;
uint takerTokenAmount;
uint makerFee;
uint takerFee;
uint expirationTimestampInSec;
bytes32 orderHash;
}
modifier onlyWhitelisted() {
require(whitelist.isWhitelisted(msg.sender));
_;
}
function Exchange(address _zrxToken, address _tokenTransferProxy, Whitelist _whitelist) {
ZRX_TOKEN_CONTRACT = _zrxToken;
TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy;
whitelist = _whitelist;
}
/*
* Core exchange functions
*/
/// @dev Fills the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Total amount of takerToken filled in trade.
function fillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8 v,
bytes32 r,
bytes32 s)
public
onlyWhitelisted
returns (uint filledTakerTokenAmount)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.taker == address(0) || order.taker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0);
require(isValidSignature(
order.maker,
order.orderHash,
v,
r,
s
));
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount);
if (filledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) {
LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash);
return 0;
}
if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) {
LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash);
return 0;
}
uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
uint paidMakerFee;
uint paidTakerFee;
filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount);
require(transferViaTokenTransferProxy(
order.makerToken,
order.maker,
msg.sender,
filledMakerTokenAmount
));
require(transferViaTokenTransferProxy(
order.takerToken,
msg.sender,
order.maker,
filledTakerTokenAmount
));
if (order.feeRecipient != address(0)) {
if (order.makerFee > 0) {
paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
order.maker,
order.feeRecipient,
paidMakerFee
));
}
if (order.takerFee > 0) {
paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
msg.sender,
order.feeRecipient,
paidTakerFee
));
}
}
LogFill(
order.maker,
msg.sender,
order.feeRecipient,
order.makerToken,
order.takerToken,
filledMakerTokenAmount,
filledTakerTokenAmount,
paidMakerFee,
paidTakerFee,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return filledTakerTokenAmount;
}
/// @dev Cancels the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order.
/// @return Amount of takerToken cancelled.
function cancelOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint cancelTakerTokenAmount)
public
onlyWhitelisted
returns (uint)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.maker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0);
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount);
if (cancelledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount);
LogCancel(
order.maker,
order.feeRecipient,
order.makerToken,
order.takerToken,
getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount),
cancelledTakerTokenAmount,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return cancelledTakerTokenAmount;
}
/*
* Wrapper functions
*/
/// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
function fillOrKillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
uint8 v,
bytes32 r,
bytes32 s)
public
{
require(fillOrder(
orderAddresses,
orderValues,
fillTakerTokenAmount,
false,
v,
r,
s
) == fillTakerTokenAmount);
}
/// @dev Synchronously executes multiple fill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fillOrKill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrKillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrKillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
/// @return Total amount of fillTakerTokenAmount filled in orders.
function fillOrdersUpTo(
address[5][] orderAddresses,
uint[6][] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
returns (uint)
{
uint filledTakerTokenAmount = 0;
for (uint i = 0; i < orderAddresses.length; i++) {
require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order
filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder(
orderAddresses[i],
orderValues[i],
safeSub(fillTakerTokenAmount, filledTakerTokenAmount),
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
));
if (filledTakerTokenAmount == fillTakerTokenAmount) break;
}
return filledTakerTokenAmount;
}
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders.
function batchCancelOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] cancelTakerTokenAmounts)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
cancelOrder(
orderAddresses[i],
orderValues[i],
cancelTakerTokenAmounts[i]
);
}
}
/*
* Constant public functions
*/
/// @dev Calculates Keccak-256 hash of order with specified parameters.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @return Keccak-256 hash of order.
function getOrderHash(address[5] orderAddresses, uint[6] orderValues)
public
constant
returns (bytes32)
{
return keccak256(
address(this),
orderAddresses[0], // maker
orderAddresses[1], // taker
orderAddresses[2], // makerToken
orderAddresses[3], // takerToken
orderAddresses[4], // feeRecipient
orderValues[0], // makerTokenAmount
orderValues[1], // takerTokenAmount
orderValues[2], // makerFee
orderValues[3], // takerFee
orderValues[4], // expirationTimestampInSec
orderValues[5] // salt
);
}
function getKeccak(bytes32 hash) public constant returns(bytes32) {
return keccak256("\x19Ethereum Signed Message:\n32", hash);
}
function getSigner(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
constant
returns (address)
{
return ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
function testRecovery(bytes32 h, uint8 v, bytes32 r, bytes32 s) returns (address) {
/* prefix might be needed for geth only
* https://github.com/ethereum/go-ethereum/issues/3731
*/
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
h = sha3(prefix, h);
address addr = ecrecover(h, v, r, s);
return addr;
}
function checkSigned(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
constant
returns (address)
{
return ecrecover(
hash,
v,
r,
s
);
}
/// @dev Verifies that an order signature is valid.
/// @param signer address of signer.
/// @param hash Signed Keccak-256 hash.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Validity of order signature.
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
constant
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
/// @dev Checks if rounding error > 0.1%.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingError(uint numerator, uint denominator, uint target)
public
constant
returns (bool)
{
uint remainder = mulmod(target, numerator, denominator);
if (remainder == 0) return false; // No rounding error.
uint errPercentageTimes1000000 = safeDiv(
safeMul(remainder, 1000000),
safeMul(numerator, target)
);
return errPercentageTimes1000000 > 1000;
}
/// @dev Calculates partial value given a numerator and denominator.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target.
function getPartialAmount(uint numerator, uint denominator, uint target)
public
constant
returns (uint)
{
return safeDiv(safeMul(numerator, target), denominator);
}
/// @dev Calculates the sum of values already filled and cancelled for a given order.
/// @param orderHash The Keccak-256 hash of the given order.
/// @return Sum of values already filled and cancelled.
function getUnavailableTakerTokenAmount(bytes32 orderHash)
public
constant
returns (uint)
{
return safeAdd(filled[orderHash], cancelled[orderHash]);
}
/*
* Internal functions
*/
/// @dev Transfers a token using TokenTransferProxy transferFrom function.
/// @param token Address of token to transferFrom.
/// @param from Address transfering token.
/// @param to Address receiving token.
/// @param value Amount of token to transfer.
/// @return Success of token transfer.
function transferViaTokenTransferProxy(
address token,
address from,
address to,
uint value)
internal
returns (bool)
{
return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value);
}
/// @dev Checks if any order transfers will fail.
/// @param order Order struct of params that will be checked.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @return Predicted result of transfers.
function isTransferable(Order order, uint fillTakerTokenAmount)
internal
constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance.
returns (bool)
{
address taker = msg.sender;
uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
if (order.feeRecipient != address(0)) {
bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT;
bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT;
uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee);
uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee);
uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee;
uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee;
if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
|| getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
|| getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
|| getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
) return false;
if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX
|| getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount)
) return false;
if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX
|| getAllowance(order.takerToken, taker) < fillTakerTokenAmount)
) return false;
} else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getBalance(order.takerToken, taker) < fillTakerTokenAmount
|| getAllowance(order.takerToken, taker) < fillTakerTokenAmount
) return false;
return true;
}
/// @dev Get token balance of an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Token balance of owner.
function getBalance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy
}
/// @dev Get allowance of token given to TokenTransferProxy by an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Allowance of token given to TokenTransferProxy by owner.
function getAllowance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy
}
/// @dev This function permits setting the Whitelist address
/// @param _whitelist Whitelist address
function setWhitelist(Whitelist _whitelist) public onlyOwner
{
whitelist = _whitelist;
}
} | Fills the input order. orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. fillTakerTokenAmount Desired amount of takerToken to fill. shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. v ECDSA signature parameter v. r ECDSA signature parameters r. s ECDSA signature parameters s. return Total amount of takerToken filled in trade. | function fillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8 v,
bytes32 r,
bytes32 s)
public
onlyWhitelisted
returns (uint filledTakerTokenAmount)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.taker == address(0) || order.taker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0);
require(isValidSignature(
order.maker,
order.orderHash,
v,
r,
s
));
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount);
if (filledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) {
LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash);
return 0;
}
if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) {
LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash);
return 0;
}
uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
uint paidMakerFee;
uint paidTakerFee;
filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount);
require(transferViaTokenTransferProxy(
order.makerToken,
order.maker,
msg.sender,
filledMakerTokenAmount
));
require(transferViaTokenTransferProxy(
order.takerToken,
msg.sender,
order.maker,
filledTakerTokenAmount
));
if (order.feeRecipient != address(0)) {
if (order.makerFee > 0) {
paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
order.maker,
order.feeRecipient,
paidMakerFee
));
}
if (order.takerFee > 0) {
paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
msg.sender,
order.feeRecipient,
paidTakerFee
));
}
}
LogFill(
order.maker,
msg.sender,
order.feeRecipient,
order.makerToken,
order.takerToken,
filledMakerTokenAmount,
filledTakerTokenAmount,
paidMakerFee,
paidTakerFee,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return filledTakerTokenAmount;
}
| 4,807,369 |
./partial_match/5/0x695fb109ac555F42f5ca2DfE39bD864aa3A15f77/sources/MISOMarket.sol | Function to add a action template to create through factory Should have operator access _template Auction template to create a auction/ | function addAuctionTemplate(address _template) external {
require(
accessControls.hasOperatorRole(msg.sender),
"MISOMarket.addAuctionTemplate: Sender must be operator"
);
_addAuctionTemplate(_template);
}
| 16,841,034 |
./full_match/1/0x2445F5dD31df8e7b0bfBFacFD7357e58a51D147d/sources/Users/tudorg/Desktop/projects/DeBa/contracts/deba/FeeRewardForwarder.sol | Sets the path for swapping tokens to the to address The `to` address is not validated to match the targetToken, so that we could first update the paths, and then, set the new target./ | function setConversionPath(address from, address to, address[] memory _uniswapRoute) public {
require(msg.sender == governance, '!governance');
require(from == _uniswapRoute[0],
"The first token of the Uniswap route must be the from token");
require(to == _uniswapRoute[_uniswapRoute.length - 1],
"The last token of the Uniswap route must be the to token");
uniswapRoutes[from][to] = _uniswapRoute;
}
| 4,870,292 |
./full_match/80001/0xB52Cfa681A32Eb2e500ED0302131B8B619D41c54/sources/contracts/2_Owner.sol | Change newChallenger newChallenger address of new owner/ | function addChalenger(address newChallenger) public isChallenger {
emit ChallengerSet(challenger, newChallenger);
challenger = newChallenger;
}
| 5,665,934 |
pragma solidity ^0.4.17;
/** @title Decentralized Identification Number (DIN) registry. */
contract DINRegistry {
struct Record {
address owner;
address resolver; // Address of the resolver contract, which can be used to find product information.
uint256 updated; // Last updated time (Unix timestamp).
}
// DIN => Record
mapping (uint256 => Record) records;
// The first DIN registered.
uint256 public genesis;
// The current DIN.
uint256 public index;
modifier only_owner(uint256 DIN) {
require(records[DIN].owner == msg.sender);
_;
}
// Log transfers of ownership.
event NewOwner(uint256 indexed DIN, address indexed owner);
// Log when new resolvers are set.
event NewResolver(uint256 indexed DIN, address indexed resolver);
// Log new registrations.
event NewRegistration(uint256 indexed DIN, address indexed owner);
/** @dev Constructor.
* @param _genesis The first DIN registered.
*/
function DINRegistry(uint256 _genesis) public {
genesis = _genesis;
index = _genesis;
// Register the genesis DIN to the account that deploys this contract.
records[_genesis].owner = msg.sender;
records[_genesis].updated = block.timestamp;
NewRegistration(_genesis, msg.sender);
}
/**
* @dev Get the owner of a specific DIN.
*/
function owner(uint256 _DIN) public view returns (address) {
return records[_DIN].owner;
}
/**
* @dev Transfer ownership of a DIN.
* @param _DIN The DIN to transfer.
* @param _owner Address of the new owner.
*/
function setOwner(uint256 _DIN, address _owner) public only_owner(_DIN) {
records[_DIN].owner = _owner;
records[_DIN].updated = block.timestamp;
NewOwner(_DIN, _owner);
}
/**
* @dev Get the address of the resolver contract for a specific DIN.
*/
function resolver(uint256 _DIN) public view returns (address) {
return records[_DIN].resolver;
}
/**
* @dev Set the resolver of a DIN.
* @param _DIN The DIN to update.
* @param _resolver Address of the resolver.
*/
function setResolver(uint256 _DIN, address _resolver) public only_owner(_DIN) {
records[_DIN].resolver = _resolver;
records[_DIN].updated = block.timestamp;
NewResolver(_DIN, _resolver);
}
/**
* @dev Get the last time a DIN was updated with a new owner or resolver.
* @param _DIN The DIN to query.
* @return _timestamp Last updated time (Unix timestamp).
*/
function updated(uint256 _DIN) public view returns (uint256 _timestamp) {
return records[_DIN].updated;
}
/**
* @dev Self-register a new DIN.
* @return _DIN The DIN that is registered.
*/
function selfRegisterDIN() public returns (uint256 _DIN) {
return registerDIN(msg.sender);
}
/**
* @dev Self-register a new DIN and set the resolver.
* @param _resolver Address of the resolver.
* @return _DIN The DIN that is registered.
*/
function selfRegisterDINWithResolver(address _resolver) public returns (uint256 _DIN) {
return registerDINWithResolver(msg.sender, _resolver);
}
/**
* @dev Register a new DIN for a specific address.
* @param _owner Account that will own the DIN.
* @return _DIN The DIN that is registered.
*/
function registerDIN(address _owner) public returns (uint256 _DIN) {
index++;
records[index].owner = _owner;
records[index].updated = block.timestamp;
NewRegistration(index, _owner);
return index;
}
/**
* @dev Register a new DIN and set the resolver.
* @param _owner Account that will own the DIN.
* @param _resolver Address of the resolver.
* @return _DIN The DIN that is registered.
*/
function registerDINWithResolver(address _owner, address _resolver) public returns (uint256 _DIN) {
index++;
records[index].owner = _owner;
records[index].resolver = _resolver;
records[index].updated = block.timestamp;
NewRegistration(index, _owner);
NewResolver(index, _resolver);
return index;
}
}
/** @title Convenience methods for DINRegistry */
contract DINRegistryUtils {
DINRegistry registry;
// Constructor
function DINRegistryUtils(DINRegistry _registry) public {
registry = _registry;
}
/**
* @dev Self-register multiple new DINs.
* @param amount The amount of DINs to register.
*/
function selfRegisterDINs(uint256 amount) public {
registerDINs(msg.sender, amount);
}
/**
* @dev Self-register multiple new DINs and set the resolver.
* @param resolver The address of the resolver.
* @param amount The amount of DINs to register.
*/
function selfRegisterDINsWithResolver(address resolver, uint256 amount) public {
registerDINsWithResolver(msg.sender, resolver, amount);
}
/**
* @dev Register multiple new DINs.
* @param owner The account that will own the DINs.
* @param amount The amount of DINs to register.
*/
function registerDINs(address owner, uint256 amount) public {
for (uint i = 0; i < amount; i++) {
registry.registerDIN(owner);
}
}
/**
* @dev Register multiple new DINs and set the resolver.
* @param owner The account that will own the DINs.
* @param resolver The address of the resolver.
* @param amount The amount of DINs to register.
*/
function registerDINsWithResolver(address owner, address resolver, uint256 amount) public {
for (uint i = 0; i < amount; i++) {
registry.registerDINWithResolver(owner, resolver);
}
}
} | Get the owner of a specific DIN./ | function owner(uint256 _DIN) public view returns (address) {
return records[_DIN].owner;
}
| 12,580,806 |
pragma solidity ^0.4.16;
// ----------------------------------------------------------------------------
//
// IDH indaHash token public sale contract
//
// For details, please visit: https://indahash.com/ico
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// SafeMath3
//
// Adapted from https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
// (no need to implement division)
//
// ----------------------------------------------------------------------------
library SafeMath3 {
function mul(uint a, uint b) internal constant returns (uint c) {
c = a * b;
assert( a == 0 || c / a == b );
}
function sub(uint a, uint b) internal constant returns (uint) {
assert( b <= a );
return a - b;
}
function add(uint a, uint b) internal constant returns (uint c) {
c = a + b;
assert( c >= a );
}
}
// ----------------------------------------------------------------------------
//
// Owned contract
//
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
// Events ---------------------------
event OwnershipTransferProposed(address indexed _from, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
// Modifier -------------------------
modifier onlyOwner {
require( msg.sender == owner );
_;
}
// Functions ------------------------
function Owned() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) onlyOwner {
require( _newOwner != owner );
require( _newOwner != address(0x0) );
OwnershipTransferProposed(owner, _newOwner);
newOwner = _newOwner;
}
function acceptOwnership() {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// ----------------------------------------------------------------------------
//
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
// Events ---------------------------
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
// Functions ------------------------
function totalSupply() constant returns (uint);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
}
// ----------------------------------------------------------------------------
//
// ERC Token Standard #20
//
// ----------------------------------------------------------------------------
contract ERC20Token is ERC20Interface, Owned {
using SafeMath3 for uint;
uint public tokensIssuedTotal = 0;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) allowed;
// Functions ------------------------
/* Total token supply */
function totalSupply() constant returns (uint) {
return tokensIssuedTotal;
}
/* Get the account balance for an address */
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/* Transfer the balance from owner's account to another account */
function transfer(address _to, uint _amount) returns (bool success) {
// amount sent cannot exceed balance
require( balances[msg.sender] >= _amount );
// update balances
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
// log event
Transfer(msg.sender, _to, _amount);
return true;
}
/* Allow _spender to withdraw from your account up to _amount */
function approve(address _spender, uint _amount) returns (bool success) {
// approval amount cannot exceed the balance
require ( balances[msg.sender] >= _amount );
// update allowed amount
allowed[msg.sender][_spender] = _amount;
// log event
Approval(msg.sender, _spender, _amount);
return true;
}
/* Spender of tokens transfers tokens from the owner's balance */
/* Must be pre-approved by owner */
function transferFrom(address _from, address _to, uint _amount) returns (bool success) {
// balance checks
require( balances[_from] >= _amount );
require( allowed[_from][msg.sender] >= _amount );
// update balances and allowed amount
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
// log event
Transfer(_from, _to, _amount);
return true;
}
/* Returns the amount of tokens approved by the owner */
/* that can be transferred by spender */
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
// ----------------------------------------------------------------------------
//
// IDH public token sale
//
// ----------------------------------------------------------------------------
contract IndaHashToken is ERC20Token {
/* Utility variable */
uint constant E6 = 10**6;
/* Basic token data */
string public constant name = "indaHash Coin";
string public constant symbol = "IDH";
uint8 public constant decimals = 6;
/* Wallet addresses - initially set to owner at deployment */
address public wallet;
address public adminWallet;
/* ICO dates */
uint public constant DATE_PRESALE_START = 1510151400; // 08-Nov-2017 14:30 UTC
uint public constant DATE_PRESALE_END = 1510758000; // 15-Nov-2017 15:00 UTC
uint public constant DATE_ICO_START = 1511967600; // 29-Nov-2017 15:00 UTC
uint public constant DATE_ICO_END = 1513782000; // 20-Dec-2017 15:00 UTC
/* ICO tokens per ETH */
uint public tokensPerEth = 3200 * E6; // rate during last ICO week
uint public constant BONUS_PRESALE = 40;
uint public constant BONUS_ICO_WEEK_ONE = 20;
uint public constant BONUS_ICO_WEEK_TWO = 10;
/* Other ICO parameters */
uint public constant TOKEN_SUPPLY_TOTAL = 400 * E6 * E6; // 400 mm tokens
uint public constant TOKEN_SUPPLY_ICO = 320 * E6 * E6; // 320 mm tokens
uint public constant TOKEN_SUPPLY_MKT = 80 * E6 * E6; // 80 mm tokens
uint public constant PRESALE_ETH_CAP = 15000 ether;
uint public constant MIN_FUNDING_GOAL = 40 * E6 * E6; // 40 mm tokens
uint public constant MIN_CONTRIBUTION = 1 ether / 20; // 0.05 Ether
uint public constant MAX_CONTRIBUTION = 300 ether;
uint public constant COOLDOWN_PERIOD = 2 days;
uint public constant CLAWBACK_PERIOD = 90 days;
/* Crowdsale variables */
uint public icoEtherReceived = 0; // Ether actually received by the contract
uint public tokensIssuedIco = 0;
uint public tokensIssuedMkt = 0;
uint public tokensClaimedAirdrop = 0;
/* Keep track of Ether contributed and tokens received during Crowdsale */
mapping(address => uint) public icoEtherContributed;
mapping(address => uint) public icoTokensReceived;
/* Keep track of participants who
/* - have received their airdropped tokens after a successful ICO */
/* - or have reclaimed their contributions in case of fialed Crowdsale */
mapping(address => bool) public airdropClaimed;
mapping(address => bool) public refundClaimed;
// Events ---------------------------
event WalletUpdated(address _newWallet);
event AdminWalletUpdated(address _newAdminWallet);
event TokensPerEthUpdated(uint _tokensPerEth);
event TokensMinted(address indexed _owner, uint _tokens, uint _balance);
event TokensIssued(address indexed _owner, uint _tokens, uint _balance, uint _etherContributed);
event Refund(address indexed _owner, uint _amount, uint _tokens);
event Airdrop(address indexed _owner, uint _amount, uint _balance);
// Basic Functions ------------------
/* Initialize (owner is set to msg.sender by Owned.Owned() */
function IndaHashToken() {
require( TOKEN_SUPPLY_ICO + TOKEN_SUPPLY_MKT == TOKEN_SUPPLY_TOTAL );
wallet = owner;
adminWallet = owner;
}
/* Fallback */
function () payable {
buyTokens();
}
// Information functions ------------
/* What time is it? */
function atNow() constant returns (uint) {
return now;
}
/* Has the minimum threshold been reached? */
function icoThresholdReached() constant returns (bool thresholdReached) {
if (tokensIssuedIco < MIN_FUNDING_GOAL) return false;
return true;
}
/* Are tokens transferable? */
function isTransferable() constant returns (bool transferable) {
if ( !icoThresholdReached() ) return false;
if ( atNow() < DATE_ICO_END + COOLDOWN_PERIOD ) return false;
return true;
}
// Owner Functions ------------------
/* Change the crowdsale wallet address */
function setWallet(address _wallet) onlyOwner {
require( _wallet != address(0x0) );
wallet = _wallet;
WalletUpdated(wallet);
}
/* Change the admin wallet address */
function setAdminWallet(address _wallet) onlyOwner {
require( _wallet != address(0x0) );
adminWallet = _wallet;
AdminWalletUpdated(adminWallet);
}
/* Change tokensPerEth before ICO start */
function updateTokensPerEth(uint _tokensPerEth) onlyOwner {
require( atNow() < DATE_PRESALE_START );
tokensPerEth = _tokensPerEth;
TokensPerEthUpdated(_tokensPerEth);
}
/* Minting of marketing tokens by owner */
function mintMarketing(address _participant, uint _tokens) onlyOwner {
// check amount
require( _tokens <= TOKEN_SUPPLY_MKT.sub(tokensIssuedMkt) );
// update balances
balances[_participant] = balances[_participant].add(_tokens);
tokensIssuedMkt = tokensIssuedMkt.add(_tokens);
tokensIssuedTotal = tokensIssuedTotal.add(_tokens);
// log the miniting
Transfer(0x0, _participant, _tokens);
TokensMinted(_participant, _tokens, balances[_participant]);
}
/* Owner clawback of remaining funds after clawback period */
/* (for use in case of a failed Crwodsale) */
function ownerClawback() external onlyOwner {
require( atNow() > DATE_ICO_END + CLAWBACK_PERIOD );
wallet.transfer(this.balance);
}
/* Transfer out any accidentally sent ERC20 tokens */
function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, amount);
}
// Private functions ----------------
/* Accept ETH during crowdsale (called by default function) */
function buyTokens() private {
uint ts = atNow();
bool isPresale = false;
bool isIco = false;
uint tokens = 0;
// minimum contribution
require( msg.value >= MIN_CONTRIBUTION );
// one address transfer hard cap
require( icoEtherContributed[msg.sender].add(msg.value) <= MAX_CONTRIBUTION );
// check dates for presale or ICO
if (ts > DATE_PRESALE_START && ts < DATE_PRESALE_END) isPresale = true;
if (ts > DATE_ICO_START && ts < DATE_ICO_END) isIco = true;
require( isPresale || isIco );
// presale cap in Ether
if (isPresale) require( icoEtherReceived.add(msg.value) <= PRESALE_ETH_CAP );
// get baseline number of tokens
tokens = tokensPerEth.mul(msg.value) / 1 ether;
// apply bonuses (none for last week)
if (isPresale) {
tokens = tokens.mul(100 + BONUS_PRESALE) / 100;
} else if (ts < DATE_ICO_START + 7 days) {
// first week ico bonus
tokens = tokens.mul(100 + BONUS_ICO_WEEK_ONE) / 100;
} else if (ts < DATE_ICO_START + 14 days) {
// second week ico bonus
tokens = tokens.mul(100 + BONUS_ICO_WEEK_TWO) / 100;
}
// ICO token volume cap
require( tokensIssuedIco.add(tokens) <= TOKEN_SUPPLY_ICO );
// register tokens
balances[msg.sender] = balances[msg.sender].add(tokens);
icoTokensReceived[msg.sender] = icoTokensReceived[msg.sender].add(tokens);
tokensIssuedIco = tokensIssuedIco.add(tokens);
tokensIssuedTotal = tokensIssuedTotal.add(tokens);
// register Ether
icoEtherReceived = icoEtherReceived.add(msg.value);
icoEtherContributed[msg.sender] = icoEtherContributed[msg.sender].add(msg.value);
// log token issuance
Transfer(0x0, msg.sender, tokens);
TokensIssued(msg.sender, tokens, balances[msg.sender], msg.value);
// transfer Ether if we're over the threshold
if ( icoThresholdReached() ) wallet.transfer(this.balance);
}
// ERC20 functions ------------------
/* Override "transfer" (ERC20) */
function transfer(address _to, uint _amount) returns (bool success) {
require( isTransferable() );
return super.transfer(_to, _amount);
}
/* Override "transferFrom" (ERC20) */
function transferFrom(address _from, address _to, uint _amount) returns (bool success) {
require( isTransferable() );
return super.transferFrom(_from, _to, _amount);
}
// External functions ---------------
/* Reclaiming of funds by contributors in case of a failed crowdsale */
/* (it will fail if account is empty after ownerClawback) */
/* While there could not have been any token transfers yet, a contributor */
/* may have received minted tokens, so the token balance after a refund */
/* may still be positive */
function reclaimFunds() external {
uint tokens; // tokens to destroy
uint amount; // refund amount
// ico is finished and was not successful
require( atNow() > DATE_ICO_END && !icoThresholdReached() );
// check if refund has already been claimed
require( !refundClaimed[msg.sender] );
// check if there is anything to refund
require( icoEtherContributed[msg.sender] > 0 );
// update variables affected by refund
tokens = icoTokensReceived[msg.sender];
amount = icoEtherContributed[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(tokens);
tokensIssuedTotal = tokensIssuedTotal.sub(tokens);
refundClaimed[msg.sender] = true;
// transfer out refund
msg.sender.transfer(amount);
// log
Transfer(msg.sender, 0x0, tokens);
Refund(msg.sender, amount, tokens);
}
/* Claiming of "airdropped" tokens in case of successful crowdsale */
/* Can be done by token holder, or by adminWallet */
function claimAirdrop() external {
doAirdrop(msg.sender);
}
function adminClaimAirdrop(address _participant) external {
require( msg.sender == adminWallet );
doAirdrop(_participant);
}
function adminClaimAirdropMultiple(address[] _addresses) external {
require( msg.sender == adminWallet );
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i]);
}
function doAirdrop(address _participant) internal {
uint airdrop = computeAirdrop(_participant);
require( airdrop > 0 );
// update balances and token issue volume
airdropClaimed[_participant] = true;
balances[_participant] = balances[_participant].add(airdrop);
tokensIssuedTotal = tokensIssuedTotal.add(airdrop);
tokensClaimedAirdrop = tokensClaimedAirdrop.add(airdrop);
// log
Airdrop(_participant, airdrop, balances[_participant]);
Transfer(0x0, _participant, airdrop);
}
/* Function to estimate airdrop amount. For some accounts, the value of */
/* tokens received by calling claimAirdrop() may be less than gas costs */
/* If an account has tokens from the ico, the amount after the airdrop */
/* will be newBalance = tokens * TOKEN_SUPPLY_ICO / tokensIssuedIco */
function computeAirdrop(address _participant) constant returns (uint airdrop) {
// return 0 if it's too early or ico was not successful
if ( atNow() < DATE_ICO_END || !icoThresholdReached() ) return 0;
// return 0 is the airdrop was already claimed
if( airdropClaimed[_participant] ) return 0;
// return 0 if the account does not hold any crowdsale tokens
if( icoTokensReceived[_participant] == 0 ) return 0;
// airdrop amount
uint tokens = icoTokensReceived[_participant];
uint newBalance = tokens.mul(TOKEN_SUPPLY_ICO) / tokensIssuedIco;
airdrop = newBalance - tokens;
}
/* Multiple token transfers from one address to save gas */
/* (longer _amounts array not accepted = sanity check) */
function transferMultiple(address[] _addresses, uint[] _amounts) external {
require( isTransferable() );
require( _addresses.length == _amounts.length );
for (uint i = 0; i < _addresses.length; i++) super.transfer(_addresses[i], _amounts[i]);
}
} | ico is finished and was not successful check if refund has already been claimed check if there is anything to refund update variables affected by refund transfer out refund log | function reclaimFunds() external {
require( atNow() > DATE_ICO_END && !icoThresholdReached() );
require( !refundClaimed[msg.sender] );
require( icoEtherContributed[msg.sender] > 0 );
tokens = icoTokensReceived[msg.sender];
amount = icoEtherContributed[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(tokens);
tokensIssuedTotal = tokensIssuedTotal.sub(tokens);
refundClaimed[msg.sender] = true;
msg.sender.transfer(amount);
Transfer(msg.sender, 0x0, tokens);
Refund(msg.sender, amount, tokens);
}
| 12,943,061 |
./full_match/80001/0x583Da11bFE498C6E5E93289D93948CDe31ce9f61/sources/contracts/Contract.sol | update the tokenURI | function updateNFT(
uint256 tokenId,
string memory _externalURI
) public onlyOwner {
_setTokenURI(tokenId, _externalURI);
}
| 9,445,815 |
./full_match/137/0xe135Ef65C2B2213C3fD56d0Bd6500A2cA147aC10/sources/contracts/drop/DropERC20.sol | Checks whether a claimer meets the claim condition's allowlist criteria. | function verifyClaimMerkleProof(
uint256 _conditionId,
address _claimer,
uint256 _quantity,
bytes32[] calldata _proofs,
uint256 _proofMaxQuantityPerTransaction
) public view returns (bool validMerkleProof, uint256 merkleProofIndex) {
ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId];
if (currentClaimPhase.merkleRoot != bytes32(0)) {
(validMerkleProof, merkleProofIndex) = MerkleProof.verify(
_proofs,
currentClaimPhase.merkleRoot,
keccak256(abi.encodePacked(_claimer, _proofMaxQuantityPerTransaction))
);
require(validMerkleProof, "not in whitelist.");
require(
!claimCondition.limitMerkleProofClaim[_conditionId].get(uint256(uint160(_claimer))),
"proof claimed."
);
require(
_proofMaxQuantityPerTransaction == 0 || _quantity <= _proofMaxQuantityPerTransaction,
"invalid quantity proof."
);
}
}
| 4,797,833 |
./full_match/56/0xAf4C2B007Dd3bFe1c2Df3e30307768764C262124/sources/project:/contracts/Deployerable.sol | Leaves the contract without deployer. It will not be possible to call `onlyDeployer` functions anymore. Can only be called by the current deployer. NOTE: Renouncing deployership will leave the contract without an deployer, thereby removing any functionality that is only available to the deployer./ | function renounceDeployership() external onlyDeployer {
_transferDeployership(address(0));
}
| 3,228,047 |
/**
*Submitted for verification at Etherscan.io on 2021-07-27
*/
// SPDX-License-Identifier: AGPL-3.0-or-later\
pragma solidity 0.7.5;
/**
* @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");
}
}
}
/**
* @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;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
/*
* Expects percentage to be trailed by 00,
*/
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
/*
* Expects percentage to be trailed by 00,
*/
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
/**
* Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol
* @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);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
/**
* @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 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);
}
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);
}
}
}
/**
* @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);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
/**
* @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);
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint );
}
interface IwOHM {
function sOHMTowOHM( uint amount ) external view returns ( uint );
function wOHMTosOHM( uint amount ) external view returns ( uint );
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim( address _recipient ) external;
}
/**
* This contract allows Olympus seed investors and advisors to claim tokens.
* It has been revised to consider claims as staked immediately for accounting purposes.
* This ensures that network ownership does not exceed disclosed levels.
* Claimants remain protected from network dilution that may arise, but claim and stake
* does not allow them to grow ownership beyond predefined levels. This change also penalizes
* sellers, since the tokens sold are still considered staked within this contract. This
* step was taken to ensure fair distribution of exposure in the network.
*/
contract InvestorClaimV2 {
/* ========== DEPENDENCIES ========== */
using SafeMath for uint;
using SafeERC20 for IERC20;
/* ========== STRUCTS ========== */
struct Term {
uint percent; // 4 decimals ( 5000 = 0.5% )
uint wClaimed; // rebase-agnostic number
uint max; // maximum nominal OHM amount can claim
}
/* ========== STATE VARIABLES ========== */
address owner; // can set terms
address newOwner; // push/pull model for changing ownership
IERC20 immutable OHM; // claim token
IERC20 immutable DAI; // payment token
ITreasury immutable treasury; // mints claim token
IStaking immutable staking; // stake OHM for sOHM
address immutable DAO; // holds non-circulating supply
IwOHM immutable wOHM; // tracks rebase-agnostic balance
mapping( address => Term ) public terms; // tracks address info
mapping( address => address ) public walletChange; // facilitates address change
uint public totalAllocated; // as percent of supply (4 decimals: 10000 = 1%)
uint public maximumAllocated; // maximum portion of supply can allocate
/* ========== CONSTRUCTOR ========== */
constructor(
address _ohm,
address _dai,
address _treasury,
address _DAO,
address _wOHM,
address _staking,
uint _maximumAllocated
) {
owner = msg.sender;
require( _ohm != address(0) );
OHM = IERC20( _ohm );
require( _dai != address(0) );
DAI = IERC20( _dai );
require( _treasury != address(0) );
treasury = ITreasury( _treasury );
require( _DAO != address(0) );
DAO = _DAO;
require( _wOHM != address(0) );
wOHM = IwOHM( _wOHM );
require( _staking != address(0) );
staking = IStaking( _staking );
maximumAllocated = _maximumAllocated;
}
/* ========== USER FUNCTIONS ========== */
/**
* @notice allows wallet to claim OHM
* @param _amount uint
*/
function claim( uint _amount ) external {
OHM.safeTransfer( msg.sender, _claim( _amount ) ); // send claimed to sender
}
/**
* @notice allows wallet to claim OHM and stake.
* @notice set _claim to true to receive sOHM in wallet.
* @param _amount uint
* @param _claimsOHM bool
*/
function stake( uint _amount, bool _claimsOHM ) external {
uint toStake = _claim( _amount ); // claim OHM with DAI
OHM.approve( address( staking ), toStake );
staking.stake( toStake, msg.sender ); // stake OHM for sender
if ( _claimsOHM ) {
staking.claim( msg.sender ); // claim sOHM for sender
}
}
/**
* @notice logic for claiming OHM
* @param _amount uint
* @return ToSend_ uint
*/
function _claim( uint _amount ) internal returns ( uint ToSend_ ) {
DAI.safeTransferFrom( msg.sender, address( this ), _amount ); // transfer DAI payment in
DAI.approve( address( treasury ), _amount ); // approve and
ToSend_ = treasury.deposit( _amount, address( DAI ), 0 ); // deposit into treasury, receive OHM
// ensure claim is within bounds
require( claimableFor( msg.sender ).div( 1e9 ) >= ToSend_, 'Not enough vested' );
require( terms[ msg.sender ].max.sub( claimed( msg.sender ) ) >= ToSend_, 'Claimed over max' );
// add amount to tracked balance
terms[ msg.sender ].wClaimed = terms[ msg.sender ].wClaimed.add( wOHM.sOHMTowOHM( ToSend_ ) );
}
/**
* @notice allows address to push terms to new address
* @param _newAddress address
*/
function pushWalletChange( address _newAddress ) external {
require( terms[ msg.sender ].percent != 0 );
walletChange[ msg.sender ] = _newAddress;
}
/**
* @notice allows new address to pull terms
* @param _oldAddress address
*/
function pullWalletChange( address _oldAddress ) external {
require( walletChange[ _oldAddress ] == msg.sender, "wallet did not push" );
walletChange[ _oldAddress ] = address(0);
terms[ msg.sender ] = terms[ _oldAddress ];
delete terms[ _oldAddress ];
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice view OHM claimable for address. DAI decimals (18).
* @param _address address
* @return uint
*/
function claimableFor( address _address ) public view returns (uint) {
Term memory info = terms[ _address ];
uint max = circulatingSupply().mul( info.percent ).div( 1e6 );
if ( max > info.max ) {
max = info.max;
}
return max.sub( claimed( _address ) ).mul( 1e9 );
}
/**
* @notice view OHM claimed by address. OHM decimals (9).
* @param _address address
* @return uint
*/
function claimed( address _address ) public view returns ( uint ) {
return wOHM.wOHMTosOHM( terms[ _address ].wClaimed );
}
/**
* @notice view circulating supply of OHM
* @notice calculated as total supply minus DAO holdings
* @return uint
*/
function circulatingSupply() public view returns ( uint ) {
return OHM.totalSupply().sub( OHM.balanceOf( DAO ) );
}
/* ========== OWNER FUNCTIONS ========== */
/**
* @notice set terms for new address
* @notice cannot lower for address or exceed maximum total allocation
* @param _address address
* @param _max uint
* @param _rate uint
* @param _hasClaimed uint
*/
function setTerms(address _address, uint _max, uint _rate, uint _hasClaimed ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _max >= terms[ _address ].max, "cannot lower amount claimable" );
require( _rate >= terms[ _address ].percent, "cannot lower vesting rate" );
require( totalAllocated.add( _rate ) <= maximumAllocated, "Cannot allocate more" );
if( terms[ _address ].max == 0 ) {
terms[ _address ].wClaimed = wOHM.sOHMTowOHM( _hasClaimed );
}
terms[ _address ].max = _max;
terms[ _address ].percent = _rate;
totalAllocated = totalAllocated.add( _rate );
}
/**
* @notice push ownership of contract
* @param _newOwner address
*/
function pushOwnership( address _newOwner ) external {
require( msg.sender == owner, "Sender is not owner" );
require( _newOwner != address(0) );
newOwner = _newOwner;
}
/**
* @notice pull ownership of contract
*/
function pullOwnership() external {
require( msg.sender == newOwner );
owner = newOwner;
newOwner = address(0);
}
/**
* @notice renounce ownership of contract (no owner)
*/
function renounceOwnership() external {
require( msg.sender == owner, "Sender is not owner" );
owner = address(0);
newOwner = address(0);
}
} | allows wallet to claim OHM and stake. set _claim to true to receive sOHM in wallet. _amount uint _claimsOHM bool/ | function stake( uint _amount, bool _claimsOHM ) external {
OHM.approve( address( staking ), toStake );
if ( _claimsOHM ) {
}
}
| 146,056 |
// SPDX-License-Identifier: MIT
// Made by Chance Vodnoy - 6/5/2021
pragma solidity ^0.8.4;
import "./helpers/Admin.sol";
// Single use contract for testing
// No hiding or revealing
contract HigherLower is Admin {
// Current bets
mapping (uint256 => mapping (address => uint)) public bets;
mapping (uint256 => uint) public betTotals;
address public currentWinner;
uint public currentGame;
// Timestamps for when to deal with bets
uint public betLength = 60;
uint public claimLength = 30;
uint public endBets;
uint public startNext;
// Events
event Bet(address player, uint amount);
event Withdraw(address player, uint amount);
event NewCurrentWinner(address winner);
event PrizesClaimed(address winner);
event NewGame(uint number);
// Errors
error TooLate(uint time);
error TooEarly(uint time);
// Modifiers
modifier onlyBefore(uint _time) {
if (block.timestamp >= _time) revert TooLate(_time);
_;
}
modifier onlyAfter(uint _time) {
if (block.timestamp <= _time) revert TooEarly(_time);
_;
}
constructor() Admin() {
currentWinner = owner();
currentGame = 1;
// Bet time = betLength seconds
endBets = block.timestamp + betLength;
// Time to collect prizes = claimLength seconds
startNext = endBets + claimLength;
// Sets the winner's bets to 0
bets[currentGame][currentWinner] = 0;
// Sets the current game's bet total to 0
betTotals[currentGame] = 0;
}
// Starts the next game
function startNextGame() public onlyAfter(startNext) {
// Winner starts as owner
currentWinner = owner();
// Starts new game
currentGame++;
endBets = block.timestamp + betLength;
startNext = endBets + claimLength;
bets[currentGame][currentWinner] = 0;
betTotals[currentGame] = 0;
emit NewGame(currentGame);
}
// Adds bet to current game
function bet() public payable onlyBefore(endBets) {
bets[currentGame][msg.sender] += msg.value;
betTotals[currentGame] += msg.value;
if (bets[currentGame][msg.sender] > bets[currentGame][currentWinner]) {
currentWinner = msg.sender;
emit NewCurrentWinner(currentWinner);
}
emit Bet(msg.sender, msg.value);
}
// Current betters can withdraw their bets if they're not the current winner
function withdraw(uint amount) public onlyBefore(endBets) {
// The current winner cannot withdraw
require(msg.sender != currentWinner);
require(amount <= bets[currentGame][msg.sender]);
require(amount <= address(this).balance);
bets[currentGame][msg.sender] -= amount;
betTotals[currentGame] -= amount;
// Send the bets they made in the current game
Address.sendValue(payable(msg.sender), bets[currentGame][msg.sender]);
emit Withdraw(msg.sender, amount);
}
// Winner claims all bets made during the game they won in
function claim() public onlyAfter(endBets) onlyBefore(startNext) {
require(msg.sender == currentWinner);
uint total = betTotals[currentGame];
// Sets the bet total to 0
betTotals[currentGame] = 0;
// Lets new game start immediately after
startNext = block.timestamp;
// Sends all bets in the current game
Address.sendValue(payable(msg.sender), total);
emit PrizesClaimed(currentWinner);
}
// View methods:
// Gets the current bet of an address
function getCurrentBet() public view returns (uint) {
return bets[currentGame][msg.sender];
}
// Gets the current total bets of the game
function getCurrentTotal() public view returns (uint) {
return betTotals[currentGame];
}
// Gets the time left before betting closes
function getTimeLeft() public view returns (uint) {
require(endBets > block.timestamp);
return endBets - block.timestamp;
}
// Gets whether the prize is claimable or not
function getClaimable() public view returns (bool) {
return block.timestamp > endBets && block.timestamp < startNext;
}
// Gets whether a new game is possible
function getNewGame() public view returns (bool) {
return block.timestamp > startNext;
}
} | Adds bet to current game | function bet() public payable onlyBefore(endBets) {
bets[currentGame][msg.sender] += msg.value;
betTotals[currentGame] += msg.value;
if (bets[currentGame][msg.sender] > bets[currentGame][currentWinner]) {
currentWinner = msg.sender;
emit NewCurrentWinner(currentWinner);
}
emit Bet(msg.sender, msg.value);
}
| 5,407,995 |
./partial_match/1/0x1f26f25F356cCa382A4F9B2A4d60966beF443b67/sources/MetaverseMassacre.sol | Gets the count of Mints left for a given account/ | function isWhitelisted(bytes32[] memory proof, address _account)
external
view
returns (bool)
{
return
MerkleProofUpgradeable.verify(
proof,
_whitelistMerkleRoot,
toBytes32(_account)
);
}
| 3,734,714 |
pragma solidity 0.6.12;
import "openzeppelin-solidity-solc6/contracts/token/ERC721/IERC721.sol";
import "openzeppelin-solidity-solc6/contracts/math/SafeMath.sol";
import "openzeppelin-solidity-solc6/contracts/access/Ownable.sol";
import "./IERC721CreatorRoyalty.sol";
import "./Marketplace/IMarketplaceSettings.sol";
import "./Payments.sol";
contract SuperRareMarketAuctionV2 is Ownable, Payments {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////
// Structs
/////////////////////////////////////////////////////////////////////////
// The active bid for a given token, contains the bidder, the marketplace fee at the time of the bid, and the amount of wei placed on the token
struct ActiveBid {
address payable bidder;
uint8 marketplaceFee;
uint256 amount;
}
// The sale price for a given token containing the seller and the amount of wei to be sold for
struct SalePrice {
address payable seller;
uint256 amount;
}
/////////////////////////////////////////////////////////////////////////
// State Variables
/////////////////////////////////////////////////////////////////////////
// Marketplace Settings Interface
IMarketplaceSettings public iMarketplaceSettings;
// Creator Royalty Interface
IERC721CreatorRoyalty public iERC721CreatorRoyalty;
// Mapping from ERC721 contract to mapping of tokenId to sale price.
mapping(address => mapping(uint256 => SalePrice)) private tokenPrices;
// Mapping of ERC721 contract to mapping of token ID to the current bid amount.
mapping(address => mapping(uint256 => ActiveBid)) private tokenCurrentBids;
// A minimum increase in bid amount when out bidding someone.
uint8 public minimumBidIncreasePercentage; // 10 = 10%
/////////////////////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////////////////////
event Sold(
address indexed _originContract,
address indexed _buyer,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event SetSalePrice(
address indexed _originContract,
uint256 _amount,
uint256 _tokenId
);
event Bid(
address indexed _originContract,
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
event AcceptBid(
address indexed _originContract,
address indexed _bidder,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event CancelBid(
address indexed _originContract,
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
/////////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////////
/**
* @dev Initializes the contract setting the market settings and creator royalty interfaces.
* @param _iMarketSettings address to set as iMarketplaceSettings.
* @param _iERC721CreatorRoyalty address to set as iERC721CreatorRoyalty.
*/
constructor(address _iMarketSettings, address _iERC721CreatorRoyalty)
public
{
require(
_iMarketSettings != address(0),
"constructor::Cannot have null address for _iMarketSettings"
);
require(
_iERC721CreatorRoyalty != address(0),
"constructor::Cannot have null address for _iERC721CreatorRoyalty"
);
// Set iMarketSettings
iMarketplaceSettings = IMarketplaceSettings(_iMarketSettings);
// Set iERC721CreatorRoyalty
iERC721CreatorRoyalty = IERC721CreatorRoyalty(_iERC721CreatorRoyalty);
minimumBidIncreasePercentage = 10;
}
/////////////////////////////////////////////////////////////////////////
// setIMarketplaceSettings
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the marketplace settings.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IMarketplaceSettings.
*/
function setMarketplaceSettings(address _address) public onlyOwner {
require(
_address != address(0),
"setMarketplaceSettings::Cannot have null address for _iMarketSettings"
);
iMarketplaceSettings = IMarketplaceSettings(_address);
}
/////////////////////////////////////////////////////////////////////////
// setIERC721CreatorRoyalty
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the IERC721CreatorRoyalty.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IERC721CreatorRoyalty.
*/
function setIERC721CreatorRoyalty(address _address) public onlyOwner {
require(
_address != address(0),
"setIERC721CreatorRoyalty::Cannot have null address for _iERC721CreatorRoyalty"
);
iERC721CreatorRoyalty = IERC721CreatorRoyalty(_address);
}
/////////////////////////////////////////////////////////////////////////
// setMinimumBidIncreasePercentage
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the minimum bid increase percentage.
* Rules:
* - only owner
* @param _percentage uint8 to set as the new percentage.
*/
function setMinimumBidIncreasePercentage(uint8 _percentage)
public
onlyOwner
{
minimumBidIncreasePercentage = _percentage;
}
/////////////////////////////////////////////////////////////////////////
// Modifiers (as functions)
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token owner is approved for the ERC721Market
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
*/
function ownerMustHaveMarketplaceApproved(
address _originContract,
uint256 _tokenId
) internal view {
IERC721 erc721 = IERC721(_originContract);
address owner = erc721.ownerOf(_tokenId);
require(
erc721.isApprovedForAll(owner, address(this)),
"owner must have approved contract"
);
}
/**
* @dev Checks that the token is owned by the sender
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
*/
function senderMustBeTokenOwner(address _originContract, uint256 _tokenId)
internal
view
{
IERC721 erc721 = IERC721(_originContract);
require(
erc721.ownerOf(_tokenId) == msg.sender,
"sender must be the token owner"
);
}
/////////////////////////////////////////////////////////////////////////
// setSalePrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setSalePrice(
address _originContract,
uint256 _tokenId,
uint256 _amount
) external {
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_originContract, _tokenId);
// The sender must be the token owner
senderMustBeTokenOwner(_originContract, _tokenId);
if (_amount == 0) {
// Set not for sale and exit
_resetTokenPrice(_originContract, _tokenId);
emit SetSalePrice(_originContract, _amount, _tokenId);
return;
}
tokenPrices[_originContract][_tokenId] = SalePrice(msg.sender, _amount);
emit SetSalePrice(_originContract, _amount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// safeBuy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchase the token with the expected amount. The current token owner must have the marketplace approved.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount expecting to purchase the token for.
*/
function safeBuy(
address _originContract,
uint256 _tokenId,
uint256 _amount
) external payable {
// Make sure the tokenPrice is the expected amount
require(
tokenPrices[_originContract][_tokenId].amount == _amount,
"safeBuy::Purchase amount must equal expected amount"
);
buy(_originContract, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// buy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchases the token if it is for sale.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token.
*/
function buy(address _originContract, uint256 _tokenId) public payable {
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_originContract, _tokenId);
// Check that the person who set the price still owns the token.
require(
_priceSetterStillOwnsTheToken(_originContract, _tokenId),
"buy::Current token owner must be the person to have the latest price."
);
SalePrice memory sp = tokenPrices[_originContract][_tokenId];
// Check that token is for sale.
require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale.");
// Check that enough ether was sent.
require(
tokenPriceFeeIncluded(_originContract, _tokenId) == msg.value,
"buy::Must purchase the token for the correct price"
);
// Get token contract details.
IERC721 erc721 = IERC721(_originContract);
address tokenOwner = erc721.ownerOf(_tokenId);
// Wipe the token price.
_resetTokenPrice(_originContract, _tokenId);
// Transfer token.
erc721.safeTransferFrom(tokenOwner, msg.sender, _tokenId);
// if the buyer had an existing bid, return it
if (_addressHasBidOnToken(msg.sender, _originContract, _tokenId)) {
_refundBid(_originContract, _tokenId);
}
// Payout all parties.
address payable owner = _makePayable(owner());
Payments.payout(
sp.amount,
!iMarketplaceSettings.hasERC721TokenSold(_originContract, _tokenId),
iMarketplaceSettings.getMarketplaceFeePercentage(),
iERC721CreatorRoyalty.getERC721TokenRoyaltyPercentage(
_originContract,
_tokenId
),
iMarketplaceSettings.getERC721ContractPrimarySaleFeePercentage(
_originContract
),
_makePayable(tokenOwner),
owner,
iERC721CreatorRoyalty.tokenCreator(_originContract, _tokenId),
owner
);
// Set token as sold
iMarketplaceSettings.markERC721Token(_originContract, _tokenId, true);
emit Sold(_originContract, msg.sender, tokenOwner, sp.amount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// tokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
* @return uint256 sale price of the token
*/
function tokenPrice(address _originContract, uint256 _tokenId)
external
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_originContract, _tokenId)) {
return tokenPrices[_originContract][_tokenId].amount;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// tokenPriceFeeIncluded
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token including the marketplace fee.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
* @return uint256 sale price of the token including the fee.
*/
function tokenPriceFeeIncluded(address _originContract, uint256 _tokenId)
public
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_originContract, _tokenId)) {
return
tokenPrices[_originContract][_tokenId].amount.add(
iMarketplaceSettings.calculateMarketplaceFee(
tokenPrices[_originContract][_tokenId].amount
)
);
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// bid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own.
* @param _newBidAmount uint256 value in wei to bid.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
*/
function bid(
uint256 _newBidAmount,
address _originContract,
uint256 _tokenId
) external payable {
// Check that bid is greater than 0.
require(_newBidAmount > 0, "bid::Cannot bid 0 Wei.");
// Check that bid is higher than previous bid
uint256 currentBidAmount =
tokenCurrentBids[_originContract][_tokenId].amount;
require(
_newBidAmount > currentBidAmount &&
_newBidAmount >=
currentBidAmount.add(
currentBidAmount.mul(minimumBidIncreasePercentage).div(100)
),
"bid::Must place higher bid than existing bid + minimum percentage."
);
// Check that enough ether was sent.
uint256 requiredCost =
_newBidAmount.add(
iMarketplaceSettings.calculateMarketplaceFee(_newBidAmount)
);
require(
requiredCost == msg.value,
"bid::Must purchase the token for the correct price."
);
// Check that bidder is not owner.
IERC721 erc721 = IERC721(_originContract);
address tokenOwner = erc721.ownerOf(_tokenId);
require(tokenOwner != msg.sender, "bid::Bidder cannot be owner.");
// Refund previous bidder.
_refundBid(_originContract, _tokenId);
// Set the new bid.
_setBid(_newBidAmount, msg.sender, _originContract, _tokenId);
emit Bid(_originContract, msg.sender, _newBidAmount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// safeAcceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token with the expected bid amount.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount of the bid
*/
function safeAcceptBid(
address _originContract,
uint256 _tokenId,
uint256 _amount
) external {
// Make sure accepting bid is the expected amount
require(
tokenCurrentBids[_originContract][_tokenId].amount == _amount,
"safeAcceptBid::Bid amount must equal expected amount"
);
acceptBid(_originContract, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// acceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token
*/
function acceptBid(address _originContract, uint256 _tokenId) public {
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_originContract, _tokenId);
// The sender must be the token owner
senderMustBeTokenOwner(_originContract, _tokenId);
// Check that a bid exists.
require(
_tokenHasBid(_originContract, _tokenId),
"acceptBid::Cannot accept a bid when there is none."
);
// Get current bid on token
ActiveBid memory currentBid =
tokenCurrentBids[_originContract][_tokenId];
// Wipe the token price and bid.
_resetTokenPrice(_originContract, _tokenId);
_resetBid(_originContract, _tokenId);
// Transfer token.
IERC721 erc721 = IERC721(_originContract);
erc721.safeTransferFrom(msg.sender, currentBid.bidder, _tokenId);
// Payout all parties.
address payable owner = _makePayable(owner());
Payments.payout(
currentBid.amount,
!iMarketplaceSettings.hasERC721TokenSold(_originContract, _tokenId),
iMarketplaceSettings.getMarketplaceFeePercentage(),
iERC721CreatorRoyalty.getERC721TokenRoyaltyPercentage(
_originContract,
_tokenId
),
iMarketplaceSettings.getERC721ContractPrimarySaleFeePercentage(
_originContract
),
msg.sender,
owner,
iERC721CreatorRoyalty.tokenCreator(_originContract, _tokenId),
owner
);
iMarketplaceSettings.markERC721Token(_originContract, _tokenId, true);
emit AcceptBid(
_originContract,
currentBid.bidder,
msg.sender,
currentBid.amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// cancelBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Cancel the bid on the token.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 ID of the token.
*/
function cancelBid(address _originContract, uint256 _tokenId) external {
// Check that sender has a current bid.
require(
_addressHasBidOnToken(msg.sender, _originContract, _tokenId),
"cancelBid::Cannot cancel a bid if sender hasn't made one."
);
// Refund the bidder.
_refundBid(_originContract, _tokenId);
emit CancelBid(
_originContract,
msg.sender,
tokenCurrentBids[_originContract][_tokenId].amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// currentBidDetailsOfToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Function to get current bid and bidder of a token.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function currentBidDetailsOfToken(address _originContract, uint256 _tokenId)
public
view
returns (uint256, address)
{
return (
tokenCurrentBids[_originContract][_tokenId].amount,
tokenCurrentBids[_originContract][_tokenId].bidder
);
}
/////////////////////////////////////////////////////////////////////////
// _priceSetterStillOwnsTheToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _originContract address of the contract storing the token.
* @param _tokenId uint256 id of the.
*/
function _priceSetterStillOwnsTheToken(
address _originContract,
uint256 _tokenId
) internal view returns (bool) {
IERC721 erc721 = IERC721(_originContract);
return
erc721.ownerOf(_tokenId) ==
tokenPrices[_originContract][_tokenId].seller;
}
/////////////////////////////////////////////////////////////////////////
// _resetTokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set token price to 0 for a given contract.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _resetTokenPrice(address _originContract, uint256 _tokenId)
internal
{
tokenPrices[_originContract][_tokenId] = SalePrice(address(0), 0);
}
/////////////////////////////////////////////////////////////////////////
// _addressHasBidOnToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the given address has an existing bid on a token.
* @param _bidder address that may have a current bid.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _addressHasBidOnToken(
address _bidder,
address _originContract,
uint256 _tokenId
) internal view returns (bool) {
return tokenCurrentBids[_originContract][_tokenId].bidder == _bidder;
}
/////////////////////////////////////////////////////////////////////////
// _tokenHasBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the token has an existing bid.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _tokenHasBid(address _originContract, uint256 _tokenId)
internal
view
returns (bool)
{
return tokenCurrentBids[_originContract][_tokenId].bidder != address(0);
}
/////////////////////////////////////////////////////////////////////////
// _refundBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to return an existing bid on a token to the
* bidder and reset bid.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _refundBid(address _originContract, uint256 _tokenId) internal {
ActiveBid memory currentBid =
tokenCurrentBids[_originContract][_tokenId];
if (currentBid.bidder == address(0)) {
return;
}
_resetBid(_originContract, _tokenId);
Payments.refund(
currentBid.marketplaceFee,
currentBid.bidder,
currentBid.amount
);
}
/////////////////////////////////////////////////////////////////////////
// _resetBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to reset bid by setting bidder and bid to 0.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _resetBid(address _originContract, uint256 _tokenId) internal {
tokenCurrentBids[_originContract][_tokenId] = ActiveBid(
address(0),
0,
0
);
}
/////////////////////////////////////////////////////////////////////////
// _setBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _amount uint256 value in wei to bid. Does not include marketplace fee.
* @param _bidder address of the bidder.
* @param _originContract address of ERC721 contract.
* @param _tokenId uin256 id of the token.
*/
function _setBid(
uint256 _amount,
address payable _bidder,
address _originContract,
uint256 _tokenId
) internal {
// Check bidder not 0 address.
require(_bidder != address(0), "Bidder cannot be 0 address.");
// Set bid.
tokenCurrentBids[_originContract][_tokenId] = ActiveBid(
_bidder,
iMarketplaceSettings.getMarketplaceFeePercentage(),
_amount
);
}
/////////////////////////////////////////////////////////////////////////
// _makePayable
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _address non-payable address
* @return payable address
*/
function _makePayable(address _address)
internal
pure
returns (address payable)
{
return address(uint160(_address));
}
}
| / setMinimumBidIncreasePercentage/ Admin function to set the minimum bid increase percentage. Rules: - only owner _percentage uint8 to set as the new percentage./ | function setMinimumBidIncreasePercentage(uint8 _percentage)
public
onlyOwner
{
minimumBidIncreasePercentage = _percentage;
}
| 5,442,329 |
pragma solidity ^0.4.18;
/**
* Shipment Tracking
*
* @title An example shipment tracking smart contract.
*/
contract ShipmentTracking {
struct Location {
string name;
string custodian;
uint arrival;
uint departure;
}
event Departed(
string location,
string custodian,
uint time,
uint index
);
event Arrived(
string location,
string custodian,
uint time,
uint index
);
event Delivered(
string location,
string custodian,
uint time
);
uint public packageId;
string public from;
string public to;
string public originName;
string public destinationName;
uint public departureTime;
uint public deliveryTime;
Location[] locations;
/**
* Constructs a contract that updates and tracks location history of a
* package throughout shipment.
* @param _packageId Unique id for the package.
* @param _from String of from entity name.
* @param _to String of to entity name.
* @param _originName String of origin place name.
* @param _destinationName String of destination place name.
* @param _custodian String of package caretaker's name.
*/
function ShipmentTracking(
uint _packageId,
string _from,
string _to,
string _originName,
string _destinationName,
string _custodian,
uint _departureTime
) public {
packageId = _packageId;
from = _from;
to = _to;
originName = _originName;
destinationName = _destinationName;
departureTime = _departureTime;
deliveryTime = 0;
locations.push(Location({
name: _originName,
custodian: _custodian,
arrival: 0,
departure: now
}));
Departed(_originName, _custodian, now, locations.length - 1);
}
/**
* @dev Fallback function
*/
function() public payable { revert(); }
/**
* Sets a location in the locations array when the package arrives
* at a new location. Also publicly alerts via `Arrived`.
* @param _name Location name.
* @param _custodian Name of the custodian of the package at this location.
* @param _arrival Unix time stamp in seconds of the arrival time.
* @return True if success.
*/
function arrive(
string _name,
string _custodian,
uint _arrival
)
public
returns (bool success)
{
if (_arrival == 0) {
_arrival = now;
}
locations.push(Location({
name: _name,
custodian: _custodian,
arrival: _arrival,
departure: 0
}));
Arrived(_name, _custodian, _arrival, locations.length - 1);
return true;
}
/**
* Sets the departure time of the location in the locations array. Also
* publicly alerts via `Departed`.
* @param _index Index of the location in the locations array.
* @param _departure Unix time stamp in seconds of the departure time.
* @return True if success.
*/
function depart(
uint _index,
uint _departure
)
public
returns (bool success)
{
if (_departure == 0) {
_departure = now;
}
locations[_index].departure = _departure;
Departed(
locations[_index].name,
locations[_index].custodian,
_departure,
_index
);
return true;
}
/**
* Sets a location in the locations array when the package arrives
* at the final destination. Also publicly alerts via `Arrived` and
* `Delivered`.
* @param _name Location name.
* @param _custodian Name of the custodian of the package at this location.
* @param _arrival Unix time stamp in seconds of the arrival time.
* @return True if success.
*/
function deliver(
string _name,
string _custodian,
uint _arrival
)
public
returns (bool success)
{
if (_arrival == 0) {
_arrival = now;
}
locations.push(Location({
name: _name,
custodian: _custodian,
arrival: _arrival,
departure: 0
}));
Arrived(_name, _custodian, _arrival, locations.length - 1);
Delivered(_name, _custodian, _arrival);
return true;
}
/**
* Gets all the details for the package contract in 1 call.
* @return Returns all of the public members of the contract.
*/
function getDetails()
public
constant
returns (uint, string, string, string, string, uint, uint)
{
return (
packageId,
from,
to,
originName,
destinationName,
departureTime,
deliveryTime
);
}
/**
* Gets all the locations in the array.
* @return Returns all locations.
*/
function getLocations()
public
constant
returns (Location[])
{
return locations;
}
}
| Gets all the details for the package contract in 1 call. return Returns all of the public members of the contract./ | function getDetails()
public
constant
returns (uint, string, string, string, string, uint, uint)
{
return (
packageId,
from,
to,
originName,
destinationName,
departureTime,
deliveryTime
);
}
| 2,506,518 |
./partial_match/42/0x2d5D0C6C199A3746BCE90a0E52B5c6CFD1df7D86/sources/UFragments.sol | info.oscilationPrice = _targetPrice; | function initRebase (address _uniswapV2PairAddress, uint256 _targetPrice) onlyOwner public {
require(!info.initialSetup);
info.initialSetup = true;
info.coinWorkingTime = now;
info.uniswapV2PairAddress = _uniswapV2PairAddress;
info.tokenETH = IUniswapV2Pair(info.uniswapV2PairAddress).token1() != address(this)
? IUniswapV2Pair(info.uniswapV2PairAddress).token1()
: IUniswapV2Pair(info.uniswapV2PairAddress).token0();
info.oscilationPrice = IERC20(info.tokenETH).balanceOf(info.uniswapV2PairAddress) / info.totalSupply;
}
| 3,339,301 |
// SPDX-License-Identifier: MIT
/*
* JuiceBox.sol
*
* Created: October 27, 2021
*
* Price: FREE
* Rinkeby: 0x09494437a042494eAdA9801A85eE494cFB27D75b
* Mainnet:
*
* Description: An ERC-721 token that will be claimable by anyone who owns 'the Plug'
*
* - There will be 4 variations, each with a different rarity (based on how likely it is
* to receive, i.e. v1:60%, v2:20%, v3:15%, v4:5%)
* - Owners with multiple Plugs will benefit through a distribution scheme that shifts
* the probability of minting each variation towards 25%
*/
pragma solidity >=0.5.16 <0.9.0;
import "./Kasbeer721.sol";
//@title Juice Box
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract JuiceBox is Kasbeer721 {
// -------------
// EVENTS & VARS
// -------------
event JuiceBoxMinted(uint256 indexed a);
event JuiceBoxBurned(uint256 indexed a);
//@dev This is how we'll keep track of who has already minted a JuiceBox
mapping (address => bool) internal _boxHolders;
//@dev Keep track of which token ID is associated with which hash
mapping (uint256 => string) internal _tokenToHash;
//@dev Initial production hashes
string [NUM_ASSETS] boxHashes = ["QmbZH1NZLvUTqeaHXH37fVnb7QHcCFDsn4QKvicM1bmn5j",
"QmVXiZFCwxBiJQJCpiSCKz8TkaWmnEBpT6stmxYqRK4FeY",
"Qmds7Ag48sfeodwmtWmTokFGZoHiGZXYN2YbojtjTR7GhR",
"QmeUPdEvAU5sSEv1Nwixbu1oxkSFCY194m8Drm9u3rtVWg"];
//cherry, berry, kiwi, lemon
//@dev Associated weights of probability for hashes
uint16 [NUM_ASSETS] boxWeights = [60, 23, 15, 2];//cherry, berry, kiwi, lemon
//@dev Secret word to prevent etherscan claims
string private _secret;
constructor(string memory secret) Kasbeer721("Juice Box", "") {
_whitelistActive = true;
_secret = secret;
_contractUri = "ipfs://QmdafigFsnSjondbSFKWhV2zbCf8qF5xEkgNoCYcnanhD6";
payoutAddress = 0x6b8C6E15818C74895c31A1C91390b3d42B336799;//logik
}
// -----------
// RESTRICTORS
// -----------
modifier boxAvailable()
{
require(getCurrentId() < MAX_NUM_TOKENS, "JuiceBox: no JuiceBox's left to mint");
_;
}
modifier tokenExists(uint256 tokenId)
{
require(_exists(tokenId), "JuiceBox: nonexistent token");
_;
}
// ---------------
// JUICE BOX MAGIC
// ---------------
//@dev Override 'tokenURI' to account for asset/hash cycling
function tokenURI(uint256 tokenId)
public view virtual override tokenExists(tokenId)
returns (string memory)
{
return string(abi.encodePacked(_baseURI(), _tokenToHash[tokenId]));
}
//@dev Get the secret word
function _getSecret() private view returns (string memory)
{
return _secret;
}
//// ----------------------
//// IPFS HASH MANIPULATION
//// ----------------------
//@dev Get the hash stored at `idx`
function getHashByIndex(uint8 idx) public view hashIndexInRange(idx)
returns (string memory)
{
return boxHashes[idx];
}
//@dev Allows us to update the IPFS hash values (one at a time)
// 0:cherry, 1:berry, 2:kiwi, 3:lemon
function updateHashForIndex(uint8 idx, string memory str)
public isSquad hashIndexInRange(idx)
{
boxHashes[idx] = str;
}
// ------------------
// MINTING & CLAIMING
// ------------------
//@dev Allows owners to mint for free
function mint(address to) public virtual override isSquad boxAvailable
returns (uint256 tid)
{
tid = _mintInternal(to);
_assignHash(tid, 1);
}
//@dev Mint a specific juice box (owners only)
function mintWithHash(address to, string memory hash) public isSquad returns (uint256 tid)
{
tid = _mintInternal(to);
_tokenToHash[tid] = hash;
}
//@dev Claim a JuiceBox if you're a Plug holder
function claim(address to, uint8 numPlugs, string memory secret) public
boxAvailable whitelistEnabled onlyWhitelist(to) saleActive
returns (uint256 tid, string memory hash)
{
require(!_boxHolders[to], "JuiceBox: cannot claim more than 1");
require(!_isContract(to), "JuiceBox: silly rabbit :P");
require(_stringsEqual(secret, _getSecret()), "JuiceBox: silly rabbit :P");
tid = _mintInternal(to);
hash = _assignHash(tid, numPlugs);
}
//@dev Mints a single Juice Box & updates `_boxHolders` accordingly
function _mintInternal(address to) internal virtual returns (uint256 newId)
{
_incrementTokenId();
newId = getCurrentId();
_safeMint(to, newId);
_markAsClaimed(to);
emit JuiceBoxMinted(newId);
}
//@dev Based on the number of Plugs owned by the sender, randomly select
// a JuiceBox hash that will be associated with their token id
function _assignHash(uint256 tid, uint8 numPlugs) private tokenExists(tid)
returns (string memory hash)
{
uint8[] memory weights = new uint8[](NUM_ASSETS);
//calculate new weights based on `numPlugs`
if (numPlugs > 15) numPlugs = 15;
weights[0] = uint8(boxWeights[0] - 35*((numPlugs-1)/10));//cherry: 60% -> 25%
weights[1] = uint8(boxWeights[1] + 2*((numPlugs-1)/10));//berry: 23% -> 25%
weights[2] = uint8(boxWeights[2] + 10*((numPlugs-1)/10));//kiwi: 15% -> 25%
weights[3] = uint8(boxWeights[3] + 23*((numPlugs-1)/10));//lemon: 2% -> 25%
uint16 rnd = random() % 100;//should be b/n 0 & 100
//randomly select a juice box hash
uint8 i;
for (i = 0; i < NUM_ASSETS; i++) {
if (rnd < weights[i]) {
hash = boxHashes[i];
break;
}
rnd -= weights[i];
}
//assign the selected hash to this token id
_tokenToHash[tid] = hash;
}
//@dev Update `_boxHolders` so that `a` cannot claim another juice box
function _markAsClaimed(address a) private
{
_boxHolders[a] = true;
}
function getHashForTid(uint256 tid) public view tokenExists(tid)
returns (string memory)
{
return _tokenToHash[tid];
}
//@dev Pseudo-random number generator
function random() public view returns (uint16 rnd)
{
return uint16(uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, boxWeights))));
}
}
// SPDX-License-Identifier: MIT
/*
* Kasbeer721.sol
*
* Created: October 27, 2021
*
* Tuned-up ERC721 that covers a multitude of features that are generally useful
* so that it can be easily extended for quick customization .
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./access/Whitelistable.sol";
import "./access/Pausable.sol";
import "./utils/LibPart.sol";
//@title Kasbeer721 - Beefed up ERC721
//@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Kasbeer721 is ERC721, Whitelistable, Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
// -------------
// EVENTS & VARS
// -------------
event Kasbeer721Minted(uint256 indexed tokenId);
event Kasbeer721Burned(uint256 indexed tokenId);
//@dev Token incrementing
Counters.Counter internal _tokenIds;
//@dev Important numbers
uint constant NUM_ASSETS = 4;//4 juice box variations
uint constant MAX_NUM_TOKENS = 111;
//@dev Properties
string internal _contractUri;
address public payoutAddress;
//@dev These are needed for contract compatability
uint256 constant public royaltyFeeBps = 1000; // 10%
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
constructor(string memory temp_name, string memory temp_symbol)
ERC721(temp_name, temp_symbol) {}
// ---------
// MODIFIERS
// ---------
modifier hashIndexInRange(uint8 idx)
{
require(0 <= idx && idx < NUM_ASSETS, "Kasbeer721: index OOB");
_;
}
modifier onlyValidTokenId(uint256 tokenId)
{
require(1 <= tokenId && tokenId <= MAX_NUM_TOKENS, "Kasbeer721: tokenId OOB");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev All of the asset's will be pinned to IPFS
function _baseURI()
internal view virtual override returns (string memory)
{
return "ipfs://";
}
//@dev This is here as a reminder to override for custom transfer functionality
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal virtual override
{
super._beforeTokenTransfer(from, to, tokenId);
}
//@dev Allows owners to mint for free
function mint(address to) public virtual isSquad returns (uint256)
{
_tokenIds.increment();
uint256 newId = _tokenIds.current();
_safeMint(to, newId);
emit Kasbeer721Minted(newId);
return newId;
}
//@dev Custom burn function - nothing special
function burn(uint256 tokenId) public virtual
{
require(
isInSquad(_msgSender()) ||
_msgSender() == ownerOf(tokenId),
"Kasbeer721: not owner or in squad."
);
_burn(tokenId);
emit Kasbeer721Burned(tokenId);
}
//// --------
//// CONTRACT
//// --------
//@dev Controls the contract-level metadata to include things like royalties
function contractURI() public view returns(string memory)
{
return _contractUri;
}
//@dev Ability to change the contract URI
function updateContractUri(string memory updatedContractUri) public isSquad
{
_contractUri = updatedContractUri;
}
//@dev Allows us to withdraw funds collected
function withdraw(address payable wallet, uint256 amount) public isSquad
{
require(amount <= address(this).balance,
"Kasbeer721: Insufficient funds to withdraw");
wallet.transfer(amount);
}
//@dev Destroy contract and reclaim leftover funds
function kill() public onlyOwner
{
selfdestruct(payable(_msgSender()));
}
// -------
// HELPERS
// -------
//@dev Returns the current token id (number minted so far)
function getCurrentId() public view returns (uint256)
{
return _tokenIds.current();
}
//@dev Increments `_tokenIds` by 1
function _incrementTokenId() internal
{
_tokenIds.increment();
}
//@dev Determine if two strings are equal using the length + hash method
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
} else {
return keccak256(A) == keccak256(B);
}
}
//@dev Determine if an address is a smart contract
function _isContract(address a) internal view returns (bool)
{
uint32 size;
assembly {
size := extcodesize(a)
}
return size > 0;
}
// -----------------
// SECONDARY MARKETS
// -----------------
//@dev Rarible Royalties V2
function getRaribleV2Royalties(uint256 id)
onlyValidTokenId(id) external view returns (LibPart.Part[] memory)
{
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account: payable(payoutAddress),
value: uint96(royaltyFeeBps)
});
return royalties;
}
//@dev EIP-2981
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) {
uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (payoutAddress, ourCut);
}
// -----------------
// INTERFACE SUPPORT
// -----------------
//@dev Confirm that this contract is compatible w/ these interfaces
function supportsInterface(bytes4 interfaceId)
public view virtual override returns (bool)
{
return interfaceId == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_ID_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
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 {
_setApprovalForAll(_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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
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 generally not needed starting with Solidity 0.8, since 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
/*
* Whitelistable.sol
*
* Created: December 21, 2021
*
* Provides functionality for a "whitelist"/"guestlist" for inheriting contracts.
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Whitelistable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Whitelistable is SquadOwnable {
// -------------
// EVENTS & VARS
// -------------
event WhitelistActivated(address indexed a);
event WhitelistDeactivated(address indexed a);
//@dev Whitelist mapping for client addresses
mapping (address => bool) internal _whitelist;
//@dev Whitelist flag for active/inactive states
bool internal _whitelistActive;
constructor() {
_whitelistActive = false;
//add myself and then logik (client)
_whitelist[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_whitelist[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;
}
// ---------
// MODIFIERS
// ---------
//@dev Determine if someone is in the whitelsit
modifier onlyWhitelist(address a)
{
require(isWhitelisted(a), "Whitelistable: must be on whitelist");
_;
}
//@dev Prevent non-whitelist minting functions from being used
modifier whitelistDisabled()
{
require(_whitelistActive == false, "Whitelistable: whitelist still active");
_;
}
//@dev Require that the whitelist is currently enabled
modifier whitelistEnabled()
{
require(_whitelistActive == true, "Whitelistable: whitelist not active");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev Toggle the state of the whitelist (on/off)
function toggleWhitelist() public isSquad
{
_whitelistActive = !_whitelistActive;
if (_whitelistActive) {
emit WhitelistActivated(_msgSender());
} else {
emit WhitelistDeactivated(_msgSender());
}
}
//@dev Determine if `a` is in the `_whitelist
function isWhitelisted(address a) public view returns (bool)
{
return _whitelist[a];
}
//// ----------
//// ADD/REMOVE
//// ----------
//@dev Add a single address to whitelist
function addToWhitelist(address a) public isSquad
{
require(!isWhitelisted(a), "Whitelistable: already whitelisted");
_whitelist[a] = true;
}
//@dev Remove a single address from the whitelist
function removeFromWhitelist(address a) public isSquad
{
require(isWhitelisted(a), "Whitelistable: not in whitelist");
_whitelist[a] = false;
}
//@dev Add a list of addresses to the whitelist
function bulkAddToWhitelist(address[] memory addresses) public isSquad
{
uint addrLen = addresses.length;
require(addrLen > 1, "Whitelistable: use `addToWhitelist` instead");
require(addrLen < 65536, "Whitelistable: cannot add more than 65535 at once");
uint16 i;
for (i = 0; i < addrLen; i++) {
if (!isWhitelisted(addresses[i])) {
_whitelist[addresses[i]] = true;
}
}
}
}
// SPDX-License-Identifier: MIT
/*
* Pausable.sol
*
* Created: December 21, 2021
*
* Provides functionality for pausing and unpausing the sale (or other functionality)
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Pausable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Pausable is SquadOwnable {
// -------------
// EVENTS & VARS
// -------------
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
constructor() {
_paused = false;
}
// ---------
// MODIFIERS
// ---------
//@dev This will require the sale to be unpaused
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
// ----------
// MAIN LOGIC
// ----------
//@dev Pause or unpause minting
function toggleSaleActive() public isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
//@dev Determine if the sale is currently paused
function paused() public view virtual returns (bool)
{
return _paused;
}
}
// SPDX-License-Identifier: MIT
/*
* LibPart.sol
*
* Author: Jack Kasbeer (taken from 'dot')
* Created: October 20, 2021
*/
pragma solidity >=0.5.16 <0.9.0;
//@dev We need this libary for Rarible
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
/*
* SquadOwnable.sol
*
* Created: December 21, 2021
*
* An extension of `Ownable.sol` to accomodate for a potential list of owners.
* NOTE: this will need to be the last inherited contract to give all parents
* access to the modifiers it provides
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
//@title SquadOwnable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract SquadOwnable is Ownable {
//@dev Ownership - list of squad members (owners)
mapping (address => bool) internal _squad;
constructor() {
//add myself and then logik (client)
_squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;
}
//@dev Custom modifier for multiple owners
modifier isSquad()
{
require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad.");
_;
}
//@dev Determine if address `a` is an approved owner
function isInSquad(address a) public view returns (bool)
{
return _squad[a];
}
//@dev Add `a` to the squad
function addToSquad(address a) public onlyOwner
{
require(!isInSquad(a), "SquadOwnable: Address already in squad.");
_squad[a] = true;
}
//@dev Remove `a` from the squad
function removeFromSquad(address a) public onlyOwner
{
require(isInSquad(a), "SquadOwnable: Address already not in squad.");
_squad[a] = false;
}
}
// 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);
}
} | Mints a single Juice Box & updates `_boxHolders` accordingly | function _mintInternal(address to) internal virtual returns (uint256 newId)
{
_incrementTokenId();
newId = getCurrentId();
_safeMint(to, newId);
_markAsClaimed(to);
emit JuiceBoxMinted(newId);
}
| 6,132,903 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IBridge.sol";
/**
* @dev Interface for bridge contract with added support for NonFungible tokens that follow the ERC-721 standard
*/
interface IBridgeNonFungible is IBridge {
/**
* @dev Transfers an ERC721 token to a different chain
* This function simply moves the caller's tokens to this contract, and emits a `TokenTransferFungible` event
*/
function transferNonFungible(address token, uint256 tokenId, uint256 networkId, bytes calldata data) external payable;
/**
* @dev Used by the bridge relay to 'transfer' a user's item to the chain
*/
function bridgeClaimNonFungible(address token, address to, uint256 tokenId) external;
event TokenTransferNonFungible(address indexed from, address indexed token, uint256 tokenId, uint256 networkId);
event TokenClaimedNonFungible(address indexed from, address indexed token, uint256 tokenId);
}
| Interface for bridge contract with added support for NonFungible tokens that follow the ERC-721 standard/ | interface IBridgeNonFungible is IBridge {
function transferNonFungible(address token, uint256 tokenId, uint256 networkId, bytes calldata data) external payable;
function bridgeClaimNonFungible(address token, address to, uint256 tokenId) external;
event TokenTransferNonFungible(address indexed from, address indexed token, uint256 tokenId, uint256 networkId);
event TokenClaimedNonFungible(address indexed from, address indexed token, uint256 tokenId);
pragma solidity ^0.8.0;
}
| 1,029,978 |
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
import "../PaymentExitDataModel.sol";
import "../routers/PaymentStandardExitRouterArgs.sol";
import "../../interfaces/ISpendingCondition.sol";
import "../../registries/SpendingConditionRegistry.sol";
import "../../utils/MoreVpFinalization.sol";
import "../../utils/OutputId.sol";
import "../../../vaults/EthVault.sol";
import "../../../vaults/Erc20Vault.sol";
import "../../../framework/PlasmaFramework.sol";
import "../../../framework/Protocol.sol";
import "../../../utils/SafeEthTransfer.sol";
import "../../../utils/PosLib.sol";
import "../../../transactions/PaymentTransactionModel.sol";
import "../../../transactions/GenericTransaction.sol";
library PaymentChallengeStandardExit {
using PosLib for PosLib.Position;
using PaymentTransactionModel for PaymentTransactionModel.Transaction;
struct Controller {
PlasmaFramework framework;
SpendingConditionRegistry spendingConditionRegistry;
uint256 safeGasStipend;
}
event ExitChallenged(
uint256 indexed utxoPos
);
/**
* @dev Data to be passed around helper functions
*/
struct ChallengeStandardExitData {
Controller controller;
PaymentStandardExitRouterArgs.ChallengeStandardExitArgs args;
PaymentExitDataModel.StandardExit exitData;
uint256 challengeTxType;
}
/**
* @notice Function that builds the controller struct
* @return Controller struct of PaymentChallengeStandardExit
*/
function buildController(
PlasmaFramework framework,
SpendingConditionRegistry spendingConditionRegistry,
uint256 safeGasStipend
)
public
pure
returns (Controller memory)
{
return Controller({
framework: framework,
spendingConditionRegistry: spendingConditionRegistry,
safeGasStipend: safeGasStipend
});
}
/**
* @notice Main logic function to challenge standard exit
* @dev emits ExitChallenged event on success
* @param self The controller struct
* @param exitMap The storage of all standard exit data
* @param args Arguments of challenge standard exit function from client
*/
function run(
Controller memory self,
PaymentExitDataModel.StandardExitMap storage exitMap,
PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args
)
public
{
require(args.senderData == keccak256(abi.encodePacked(msg.sender)), "Incorrect senderData");
GenericTransaction.Transaction memory challengeTx = GenericTransaction.decode(args.challengeTx);
ChallengeStandardExitData memory data = ChallengeStandardExitData({
controller: self,
args: args,
exitData: exitMap.exits[args.exitId],
challengeTxType: challengeTx.txType
});
verifyChallengeExitExists(data);
verifyChallengeTxProtocolFinalized(data);
verifySpendingCondition(data);
exitMap.exits[args.exitId].exitable = false;
SafeEthTransfer.transferRevertOnError(msg.sender, data.exitData.bondSize, self.safeGasStipend);
emit ExitChallenged(data.exitData.utxoPos);
}
function verifyChallengeExitExists(ChallengeStandardExitData memory data) private pure {
require(data.exitData.exitable == true, "The exit does not exist");
}
function verifyChallengeTxProtocolFinalized(ChallengeStandardExitData memory data) private view {
bool isProtocolFinalized = MoreVpFinalization.isProtocolFinalized(data.controller.framework, data.args.challengeTx);
// MoreVP protocol finalization would only return false only when tx does not exists.
// Should fail already in early stages (eg. decode)
assert(isProtocolFinalized);
}
function verifySpendingCondition(ChallengeStandardExitData memory data) private view {
PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args = data.args;
PosLib.Position memory utxoPos = PosLib.decode(data.exitData.utxoPos);
FungibleTokenOutputModel.Output memory output = PaymentTransactionModel
.decode(args.exitingTx)
.getOutput(utxoPos.outputIndex);
ISpendingCondition condition = data.controller.spendingConditionRegistry.spendingConditions(
output.outputType, data.challengeTxType
);
require(address(condition) != address(0), "Spending condition contract not found");
bytes32 outputId = data.controller.framework.isDeposit(utxoPos.blockNum)
? OutputId.computeDepositOutputId(args.exitingTx, utxoPos.outputIndex, utxoPos.encode())
: OutputId.computeNormalOutputId(args.exitingTx, utxoPos.outputIndex);
require(outputId == data.exitData.outputId, "Invalid exiting tx causing outputId mismatch");
bool isSpentByChallengeTx = condition.verify(
args.exitingTx,
utxoPos.encode(),
args.challengeTx,
args.inputIndex,
args.witness
);
require(isSpentByChallengeTx, "Spending condition failed");
}
}
| Main logic function to challenge standard exit emits ExitChallenged event on success self The controller struct exitMap The storage of all standard exit data args Arguments of challenge standard exit function from client/ | function run(
Controller memory self,
PaymentExitDataModel.StandardExitMap storage exitMap,
PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args
)
public
{
require(args.senderData == keccak256(abi.encodePacked(msg.sender)), "Incorrect senderData");
GenericTransaction.Transaction memory challengeTx = GenericTransaction.decode(args.challengeTx);
ChallengeStandardExitData memory data = ChallengeStandardExitData({
controller: self,
args: args,
exitData: exitMap.exits[args.exitId],
challengeTxType: challengeTx.txType
});
verifyChallengeExitExists(data);
verifyChallengeTxProtocolFinalized(data);
verifySpendingCondition(data);
exitMap.exits[args.exitId].exitable = false;
SafeEthTransfer.transferRevertOnError(msg.sender, data.exitData.bondSize, self.safeGasStipend);
emit ExitChallenged(data.exitData.utxoPos);
}
| 12,653,477 |
./full_match/100/0xEBbe2468DC96eeB747f1007db2070B3011f3EE9D/sources/contracts/official/TAR2/TAR2Token.sol | Gets the amount of interest the specified period pays Retorna a porcentagem de interesse que o periodo especificado paga/ | function getPeriodInterest(uint256 _nPeriod) public view returns (uint256) {
if (_nPeriod >= arrInterests.length) {
return 0;
}
return arrInterests[_nPeriod];
}
| 14,272,741 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./DBH.sol";
import "./DBUX.sol";
contract Dojo is IERC721Receiver, Ownable, Pausable
{
struct Stake {
address owner;
uint256 time;
}
event TokenStaked(address owner, uint256 tokenId);
event TokenUnstaked(uint256 tokenId, uint256 earned);
mapping(uint256 => Stake) public dojo;
mapping(address => uint16[]) public ownedTokens; // Mapping from owner to array of staked token IDs
mapping(address => uint256) public ownedTokenCount; // Mapping from owner to staked token count
mapping(uint256 => uint256) public ownedTokensIndex; // Mapping from token ID to index in ownedTokens
uint256 public dickbucksPerDay = 5000 ether;
DBH dickbutt;
DBUX dickbucks;
constructor(address _dickbutt, address _dickbucks)
{
dickbutt = DBH(_dickbutt);
dickbucks = DBUX(_dickbucks);
}
/**
* Stakes Dickbutt Heroes tokens in the Dojo, earning DBUX in the process
* @param tokenIds array of DBH token IDs owned by caller
*/
function addDickbuttsToDojo(uint16[] calldata tokenIds) external whenNotPaused
{
for(uint i = 0; i < tokenIds.length; i++) {
require(_msgSender() == dickbutt.ownerOf(tokenIds[i]), "Not your token");
dickbutt.transferFrom(_msgSender(), address(this), tokenIds[i]);
addDickbuttToDojo(_msgSender(), tokenIds[i]);
}
}
/**
* Unstakes Dickbutt Heroes tokens from the Dojo and credits owner with earned DBUX
* @param tokenIds array of DBH token IDs owned by caller
*/
function removeDickbuttsFromDojo(uint16[] calldata tokenIds) external whenNotPaused
{
for(uint i = 0; i < tokenIds.length; i++) {
require(_msgSender() == dojo[tokenIds[i]].owner, "Can't touch this");
dickbutt.transferFrom(address(this), dojo[tokenIds[i]].owner, tokenIds[i]);
removeDickbuttFromDojo(tokenIds[i]);
}
}
/**
* Credits owner with earned DBUX
* @param tokenIds array of DBH token IDs owned by caller
*/
function collectDickbucks(uint16[] calldata tokenIds) external whenNotPaused
{
for(uint i = 0; i < tokenIds.length; i++) {
require(_msgSender() == dojo[tokenIds[i]].owner, "Can't touch this");
creditEarned(tokenIds[i]);
dojo[tokenIds[i]].time = uint256(block.timestamp);
}
}
/**
* Used for rescuing Dickbutts in the event Dojo contract is permanently paused due
* to deprecation. Note: DBUX are not credited when using this method.
* @param tokenIds array of DBH token IDs owned by caller
*/
function rescue(uint16[] calldata tokenIds) external whenPaused
{
for(uint i = 0; i < tokenIds.length; i++) {
require(_msgSender() == dojo[tokenIds[i]].owner, "Can't touch this");
dickbutt.transferFrom(address(this), dojo[tokenIds[i]].owner, tokenIds[i]);
clearDojo(tokenIds[i], dojo[tokenIds[i]].owner);
}
}
function pause() external onlyOwner
{
_pause();
}
function unpause() external onlyOwner
{
_unpause();
}
/**
* Set the number of DBUX earned per day
* @param _dickbucksPerDay DBUX earned per day in Wei-equivalent (1000000000000000000 = 1 DBUX)
*/
function setDickbucksPerDay(uint256 _dickbucksPerDay) external onlyOwner
{
dickbucksPerDay = _dickbucksPerDay;
}
function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4)
{
require(from == address(0x0), "Do not send to Dojo directly");
return IERC721Receiver.onERC721Received.selector;
}
/**
* Adds DBH token to Dojo, setting properties necessary to track ownership and DBUX earnings
*/
function addDickbuttToDojo(address owner, uint256 tokenId) private
{
dojo[tokenId] = Stake({
owner: owner,
time : uint256(block.timestamp)
});
ownedTokensIndex[tokenId] = ownedTokens[owner].length;
ownedTokens[owner].push(uint16(tokenId));
ownedTokenCount[owner]++;
emit TokenStaked(owner, tokenId);
}
/**
* Removes DBH token from Dojo and credits owner with earned DBUX
*/
function removeDickbuttFromDojo(uint256 tokenId) private
{
uint256 earned = creditEarned(tokenId);
clearDojo(tokenId, dojo[tokenId].owner);
emit TokenUnstaked(tokenId, earned);
}
/**
* Credits owner with earned DBUX
*/
function creditEarned(uint256 tokenId) private returns (uint256)
{
address owner = dojo[tokenId].owner;
uint256 secondsStaked = uint256(block.timestamp) - uint256(dojo[tokenId].time);
// DBUX earnings multiply by number of days staked up to a max of 5
// i.e. 2 days staked = double earnings, 3 days staked = triple earnings, etc.
uint256 multiplier = (secondsStaked / 86400) + 1;
if(multiplier > 5) multiplier = 5;
uint256 earned = (dickbucksPerDay / 86400) * secondsStaked * multiplier;
uint256 rand = random(tokenId);
// There is a 13% chance of DBH being "injured" per day staked, starting with day 2
// and up to max of 52%. Injury may lead to some earned DBUX being forfeited.
if((rand & 0xffff) % 100 < (multiplier - 1) * 13) {
// 18% of earnings per day staked may potentially be forfeited (up to 5 days/90%)
// i.e. 2 days staked = up to 36%, 3 days staked = up to 54%, etc.
earned = (earned / 100) * (100 - (((rand >> 16) & 0xffff) % (multiplier * 18)));
}
if(earned > 0) {
dickbucks.mint(owner, earned);
}
return earned;
}
/**
* Clears properties tracking ownership and DBUX earnings
*/
function clearDojo(uint256 tokenId, address owner) private
{
uint256 lastTokenIndex = ownedTokens[owner].length - 1;
uint256 tokenIndex = ownedTokensIndex[tokenId];
if(tokenIndex != lastTokenIndex) {
uint256 lastTokenId = ownedTokens[owner][lastTokenIndex];
ownedTokens[owner][tokenIndex] = uint16(lastTokenId);
ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete ownedTokensIndex[tokenId];
ownedTokens[owner].pop();
ownedTokenCount[owner]--;
delete dojo[tokenId];
}
function random(uint256 seed) internal view returns (uint256)
{
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
}
// SPDX-License-Identifier: MIT
// The official ERC20 currency token of the Dickbutt ecosystem
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract DBUX is ERC20, Ownable
{
mapping(address => bool) controllers;
constructor() ERC20("Dickbucks", "DBUX") {}
function mint(address to, uint256 amount) external onlyController
{
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyController
{
_burn(from, amount);
}
function addController(address controller) external onlyOwner
{
controllers[controller] = true;
}
function removeController(address controller) external onlyOwner
{
controllers[controller] = false;
}
modifier onlyController()
{
require(controllers[_msgSender()] == true, "Caller is not controller");
_;
}
}
// SPDX-License-Identifier: MIT
/*
DickbuttH
eroesDickbuttHero
esDickbuttHeroesDickbutt
HeroesDickbuttH eroesDic
kbuttHeroesDi ckbuttH
eroesDickbuttHe roesDi
ckbuttHeroesDick buttH
eroesDickbu ttHero esDickbuttH eroes
DickbuttHeroesDickb uttHeroesDickbu ttHe
roesDickbuttHeroe sDickbuttHeroesDickbu
ttHer oesDickbutt HeroesDickbuttHeroesD
ickbuttHeroesDickbut tHeroesDick buttHeroe
sDickbuttHeroesDick buttHeroesDickbuttHer
oesDickbuttHeroesDickbuttHeroesDickb uttHe
roesD ickbuttHeroesDickb uttHer
oesDi ckbuttH eroesD
ickbut tHeroe
sDickb uttHer
oesDic kbuttH
eroes Dick buttHe
roes Dickb utt Heroes
Dick buttHeroes Dickb uttHeroes
Dickb uttHeroes Dickb uttHeroesDic
kbutt HeroesDick buttH eroesD ickb
uttHe roesDickb uttHe roesDic kbutt
Heroe sDickbutt Heroes Dickbut tHero
esDic kbuttHer oesDickbuttHeroesDic kbuttHe roesD
ickb uttHeroe sDickbuttHeroesDickbuttHeroe sDick
butt HeroesD ickbu ttHer oesDickbut tHeroe
sDic kbuttHer oes DickbuttHeroesDic kbuttH
eroes Dickb uttHe roesDickbuttHeroes Dickbut
tHer oesDi ckbuttH eroesDickbuttHeroes Dickbutt
Heroe sDickbuttHeroe sDickbut tHeroesDi
ckbut tHeroesDickb uttH eroesD ickb uttHe
roesDi ckbu ttHe roesDi ckbuttHe
roesDi ckb uttHe roes
Dickbutt Hero esDic kbut
tHeroes Dick buttHeroesDick
but tHeroesDic kbut tHeroesDickbutt
HeroesD ickbuttHeroesDick but tHeroes D
ickbuttHeroesD ickbuttHeroesDickbutt Hero esDickb
uttH eroesDickbuttH eroesDickbuttHe roesDickbuttHeroesDic
kbut tHeroesDic kbuttHeroes DickbuttHeroesDickb
uttH eroesD ickbuttHeroe sDick buttHeroesD
ickbuttHer oesDickbutt Hero
esDickb uttHeroe sDic
kbu ttHero esDi
ckbutt Hero
esDickbutt
HeroesD
ick
*/
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract DBH is ERC721Enumerable, Ownable
{
uint256 constant NUM_GENS = 3; // Number of Dickbutt Heroes generations
uint256 constant TOKENS_PER_GEN = 3333; // Number of tokens per generation
uint256 public maxPreSaleId = 359;
uint256 public maxPublicId = TOKENS_PER_GEN;
uint256 public price = .05 ether; // .05 ETH mint price
uint256 public preSalePrice = .025 ether; // .025 ETH pre-sale mint price
bool public hasSaleStarted = false; // Sale disabled by default
bool public hasPreSaleStarted = false; // Pre-sale disabled by default
mapping(address => mapping(uint256 => bool)) public hasMintedPreSale;
string public contractURI;
string public baseTokenURI;
address public dojo;
constructor(string memory _baseTokenURI, string memory _contractURI) ERC721("Dickbutt Heroes", "DBH")
{
setBaseTokenURI(_baseTokenURI);
contractURI = _contractURI;
}
/* PUBLIC/EXTERNAL */
function mint(uint256 quantity) external payable
{
require(hasSaleStarted || _msgSender() == owner(), "Sale hasn't started");
require(quantity > 0 && quantity <= 10, "Quantity must be 1-10");
require(totalSupply() + 1 <= maxPublicId, "All tokens have been minted");
require(totalSupply() + quantity <= maxPublicId, "Quantity would exceed supply");
require(msg.value >= price * quantity || _msgSender() == owner(), "Insufficient Ether sent");
mintDickbutts(_msgSender(), quantity);
}
function preSaleMint(uint256 quantity) external payable
{
require(totalSupply() + 1 <= maxPreSaleId, "All pre-sale tokens have been minted");
require(quantity > 0 && quantity <= 3, "Quantity must be 1-3");
require(totalSupply() + quantity <= maxPreSaleId, "Quantity would exceed supply");
if(_msgSender() != owner()) {
require(hasPreSaleStarted, "Pre-sale hasn't started");
require(!hasMintedPreSale[_msgSender()][calculateGen(totalSupply() + 1)], "Limit 1 pre-sale mint per address");
require(msg.value >= preSalePrice * quantity, "Insufficient Ether sent");
}
hasMintedPreSale[_msgSender()][calculateGen(totalSupply() + 1)] = true;
mintDickbutts(_msgSender(), quantity);
}
function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner
{
baseTokenURI = _baseTokenURI;
}
function setContractURI(string memory _contractURI) public onlyOwner
{
contractURI = _contractURI;
}
function setDojo(address _dojo) external onlyOwner
{
dojo = _dojo;
}
function setPrice(uint256 _price) external onlyOwner
{
price = _price;
}
function setPreSalePrice(uint256 _price) external onlyOwner
{
preSalePrice = _price;
}
function setMaxPreSaleId(uint256 newMaxId) external onlyOwner
{
require(newMaxId <= TOKENS_PER_GEN * NUM_GENS);
maxPreSaleId = newMaxId;
}
function setMaxPublicId(uint256 newMaxId) external onlyOwner
{
require(newMaxId <= TOKENS_PER_GEN * NUM_GENS);
maxPublicId = newMaxId;
}
function flipSaleStatus() external onlyOwner
{
hasSaleStarted = !hasSaleStarted;
}
function flipPreSaleStatus() external onlyOwner
{
hasPreSaleStarted = !hasPreSaleStarted;
}
function withdraw(uint256 _amount) external payable onlyOwner
{
require(payable(owner()).send(_amount));
}
function withdrawAll() external payable onlyOwner
{
require(payable(owner()).send(address(this).balance));
}
function transferFrom(address from, address to, uint256 tokenId) public virtual override
{
if(_msgSender() == dojo) {
// Hard-code approval if Dojo is doing the transfer to prevent wasted gas
_transfer(from, to, tokenId);
}
else {
super.transferFrom(from, to, tokenId);
}
}
/* PRIVATE/INTERNAL */
function mintDickbutts(address recipient, uint256 quantity) private
{
for(uint256 i = 1; i <= quantity; i++) {
_safeMint(recipient, totalSupply() + 1);
}
}
function _baseURI() internal view virtual override returns (string memory)
{
return baseTokenURI;
}
function calculateGen(uint256 tokenId) private pure returns (uint256)
{
return ((tokenId - 1) / TOKENS_PER_GEN) + 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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 Contracts guidelines: functions revert
* instead 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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 this function is
* overridden;
*
* 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 override 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");
unchecked {
_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");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev 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 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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract 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();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
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 {
_setApprovalForAll(_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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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 {}
}
// 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 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
} | Unstakes Dickbutt Heroes tokens from the Dojo and credits owner with earned DBUX tokenIds array of DBH token IDs owned by caller/ | function removeDickbuttsFromDojo(uint16[] calldata tokenIds) external whenNotPaused
{
for(uint i = 0; i < tokenIds.length; i++) {
require(_msgSender() == dojo[tokenIds[i]].owner, "Can't touch this");
dickbutt.transferFrom(address(this), dojo[tokenIds[i]].owner, tokenIds[i]);
removeDickbuttFromDojo(tokenIds[i]);
}
}
| 12,240,726 |
./full_match/4/0xB7CaaE896Dd04a1348770dd8F78AcB73b606E676/sources/TokenFarm.sol | When user register to participate in a game / | function addGameInfoToUserData(
address addr,
uint256 gameId,
uint8 answerId,
uint256 amount
) public returns (bool success) {
if (userDataStructs[addr].balance >= amount) {
userDataStructs[addr].balance =
userDataStructs[addr].balance -
amount;
userDataStructs[addr].gameInfoStructs[gameId].gameId = gameId;
userDataStructs[addr].gameInfoStructs[gameId].answerId = answerId;
userDataStructs[addr].gameInfoStructs[gameId].amount = amount;
userDataStructs[addr].gameInfoStructs[gameId].isCorrect = false;
userDataStructs[addr].gameInfoStructs[gameId].isNotified = false;
return true;
}
return false;
}
AddGameInfoInterface addGameInfoContract =
AddGameInfoInterface(AddGameInfoAddress);
| 12,443,330 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
string airlineName;
bool airlineRegistered;
bool airlinePaidFunds; //If it paid 10 Ether and can now participate.
}
mapping(address => Airline) private airlines;
mapping(address => uint256) private insurance;
mapping(address => bool) private flights; //To state that a flight is registered.
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
airlines[msg.sender] = Airline({
airlineName: "Airline_A",
airlineRegistered: true,
airlinePaidFunds: false
});
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external {
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airline, string nameOfAirline)
external
requireIsOperational
{
airlines[airline] = Airline({
airlineName: nameOfAirline,
airlineRegistered: true,
airlinePaidFunds: false
});
}
function returnRegistrationStatus() public returns (bool) {
return airlines[msg.sender].airlineRegistered;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address flight) external payable requireIsOperational {
require(flights[flight]); //Flight has to be registered.
require(msg.value > 0 && msg.value <= 1 ether);
insurance[msg.sender] = msg.value; //Passenger paid for the insurance.
}
function flightData(address flight) public requireIsOperational {
//I added this function to state that a flight is now registered.
flights[flight] = true;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(address passenger) external requireIsOperational {
uint256 value = insurance[passenger];
value = (value.mul(3)).div(2);
//value = value + 50000000000000000;
insurance[passenger] = value;
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay() public payable requireIsOperational {
uint256 value = insurance[msg.sender];
insurance[msg.sender] = 0;
(msg.sender).transfer(value);
}
function amountAPersonHas() public returns (uint256) {
//I added this function to check how much a requester has in his account.
return insurance[msg.sender];
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address sender) public payable requireIsOperational {
airlines[sender].airlinePaidFunds = true; //Airline paid the 10 ether.
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
//fund(msg.sender);
}
}
| I added this function to check how much a requester has in his account. | function amountAPersonHas() public returns (uint256) {
return insurance[msg.sender];
}
| 2,549,152 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v3-core/contracts/libraries/SafeCast.sol";
import "./IUniswapPCVController.sol";
import "../refs/UniRef.sol";
import "../utils/Timed.sol";
import "../utils/Roots.sol";
/// @title a IUniswapPCVController implementation for ERC20
/// @author Ring Protocol
contract ERC20UniswapPCVController is IUniswapPCVController, UniRef, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint128;
using SafeMathCopy for uint256;
using SafeCast for uint256;
using Roots for uint256;
uint256 public override reweightWithdrawBPs = 9900;
uint256 internal _reweightDuration = 4 hours;
uint256 internal constant BASIS_POINTS_GRANULARITY = 10000;
uint24 public override fee = 500;
/// @notice returns the linked pcv deposit contract
IPCVDeposit public override pcvDeposit;
/// @notice gets the RUSD reward incentive for reweighting
uint256 public override reweightIncentiveAmount;
Decimal.D256 internal _minDistanceForReweight;
/// @notice ERC20UniswapPCVController constructor
/// @param _core Ring Core for reference
/// @param _pcvDeposit PCV Deposit to reweight
/// @param _oracle oracle for reference
/// @param _incentiveAmount amount of RUSD for triggering a reweight
/// @param _minDistanceForReweightBPs minimum distance from peg to reweight in basis points
/// @param _pool Uniswap V3 pool contract to reweight
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router
constructor(
address _core,
address _pcvDeposit,
address _oracle,
uint256 _incentiveAmount,
uint256 _minDistanceForReweightBPs,
address _pool,
address _nft,
address _router
) UniRef(_core, _pool, _nft, _router, _oracle) Timed(_reweightDuration) {
pcvDeposit = IPCVDeposit(_pcvDeposit);
reweightIncentiveAmount = _incentiveAmount;
_minDistanceForReweight = Decimal.ratio(
_minDistanceForReweightBPs,
BASIS_POINTS_GRANULARITY
);
// start timer
_initTimed();
}
/// @notice reweights the linked PCV Deposit to the peg price. Needs to be reweight eligible
function reweight() external override whenNotPaused {
require(
reweightEligible(),
"ERC20UniswapPCVController: Not passed reweight time or not at min distance"
);
_reweight();
_incentivize();
}
/// @notice reinvest the fee income into the linked PCV Deposit.
function reinvest() external override whenNotPaused {
pcvDeposit.collect();
pcvDeposit.deposit();
emit Reinvest(msg.sender);
}
/// @notice reweights regardless of eligibility
function forceReweight() external override onlyGuardianOrGovernor {
_reweight();
}
/// @notice sets the target PCV Deposit address
function setPCVDeposit(address _pcvDeposit) external override onlyGovernor {
pcvDeposit = IPCVDeposit(_pcvDeposit);
emit PCVDepositUpdate(_pcvDeposit);
}
/// @notice sets the target PCV Deposit parameters
function setPCVDepositParameters(uint24 _fee, int24 _tickLower, int24 _tickUpper) external override onlyGovernor {
pcvDeposit.withdraw(address(pcvDeposit), pcvDeposit.totalLiquidity());
pcvDeposit.burnAndReset(_fee, _tickLower, _tickUpper);
pcvDeposit.deposit();
emit PCVDepositParametersUpdate(address(pcvDeposit), fee, _tickLower, _tickUpper);
}
/// @notice sets the reweight incentive amount
function setReweightIncentive(uint256 amount)
external
override
onlyGovernor
{
reweightIncentiveAmount = amount;
emit ReweightIncentiveUpdate(amount);
}
/// @notice sets the reweight withdrawal BPs
function setReweightWithdrawBPs(uint256 _reweightWithdrawBPs)
external
override
onlyGovernor
{
require(_reweightWithdrawBPs <= BASIS_POINTS_GRANULARITY, "ERC20UniswapPCVController: withdraw percent too high");
reweightWithdrawBPs = _reweightWithdrawBPs;
emit ReweightWithdrawBPsUpdate(_reweightWithdrawBPs);
}
/// @notice sets the reweight min distance in basis points
function setReweightMinDistance(uint256 basisPoints)
external
override
onlyGovernor
{
_minDistanceForReweight = Decimal.ratio(
basisPoints,
BASIS_POINTS_GRANULARITY
);
emit ReweightMinDistanceUpdate(basisPoints);
}
/// @notice sets the reweight duration
function setDuration(uint256 _duration)
external
override
onlyGovernor
{
_setDuration(_duration);
}
/// @notice sets the fee
function setFee(uint24 _fee) external override onlyGovernor {
fee = _fee;
emit SwapFeeUpdate(_fee);
}
/// @notice signal whether the reweight is available. Must have incentive parity and minimum distance from peg
function reweightEligible() public view override returns (bool) {
bool magnitude =
_getDistanceToPeg().greaterThan(_minDistanceForReweight);
// incentive parity is achieved after a certain time relative to distance from peg
bool time = isTimeEnded();
return magnitude && time;
}
/// @notice minimum distance as a percentage from the peg for a reweight to be eligible
function minDistanceForReweight()
external
view
override
returns (Decimal.D256 memory)
{
return _minDistanceForReweight;
}
function _incentivize() internal ifMinterSelf {
rusd().mint(msg.sender, reweightIncentiveAmount);
}
function _reweight() internal {
_withdraw();
_returnToPeg();
// resupply PCV at peg ratio
uint256 balance = IERC20(token()).balanceOf(address(this));
// transfer the entire pcv erc20 token balance to pcvDeposit, then run deposit
TransferHelper.safeTransfer(token(), address(pcvDeposit), balance);
pcvDeposit.deposit();
_burnRusdHeld();
// reset timer
_initTimed();
emit Reweight(msg.sender);
}
function _returnToPeg() internal {
Decimal.D256 memory _peg = peg();
require(
_isBelowPeg(_peg),
"ERC20UniswapPCVController: already at or above peg"
);
_swapErc20();
}
function _swapErc20() internal {
uint256 balance = IERC20(token()).balanceOf(address(this));
if (balance != 0) {
uint256 endOfTime = uint256(-1);
address _token = token();
address _rusd = address(rusd());
Decimal.D256 memory _peg = (_token < _rusd) ? peg() : invert(peg());
uint160 priceLimit = _peg.mul(2**96).asUint256().mul(2**96).sqrt().toUint160();
router.exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: _token,
tokenOut: _rusd,
fee: fee,
recipient: address(this),
deadline: endOfTime,
amountIn: balance,
amountOutMinimum: 0,
sqrtPriceLimitX96: priceLimit
})
);
}
}
function _withdraw() internal {
// Only withdraw a portion to prevent rounding errors on Uni LP dust
uint256 value =
pcvDeposit.totalLiquidity().mul(reweightWithdrawBPs) /
BASIS_POINTS_GRANULARITY;
require(value > 0, "ERC20UniswapPCVController: No liquidity to withdraw");
pcvDeposit.withdraw(address(this), value);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPCVDeposit.sol";
import "../external/Decimal.sol";
/// @title a Uniswap PCV Controller interface
/// @author Ring Protocol
interface IUniswapPCVController {
// ----------- Events -----------
event Reweight(address indexed _caller);
event Reinvest(address indexed _caller);
event PCVDepositUpdate(address indexed _pcvDeposit);
event PCVDepositParametersUpdate(address indexed pcvDeposit, uint24 fee, int24 tickLower, int24 tickUpper);
event ReweightIncentiveUpdate(uint256 _amount);
event ReweightMinDistanceUpdate(uint256 _basisPoints);
event ReweightWithdrawBPsUpdate(uint256 _reweightWithdrawBPs);
event SwapFeeUpdate(uint24 _fee);
// ----------- State changing API -----------
function reweight() external;
function reinvest() external;
// ----------- Governor only state changing API -----------
function forceReweight() external;
function setPCVDeposit(address _pcvDeposit) external;
function setPCVDepositParameters(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
function setDuration(uint256 _duration) external;
function setReweightIncentive(uint256 amount) external;
function setReweightMinDistance(uint256 basisPoints) external;
function setReweightWithdrawBPs(uint256 _reweightWithdrawBPs) external;
function setFee(uint24 _fee) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function pcvDeposit() external view returns (IPCVDeposit);
function reweightIncentiveAmount() external view returns (uint256);
function reweightEligible() external view returns (bool);
function reweightWithdrawBPs() external view returns (uint256);
function minDistanceForReweight()
external
view
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
/// @title UniRef interface
/// @author Ring Protocol
interface IUniRef {
// ----------- Events -----------
event PoolUpdate(address indexed _pool);
// ----------- Governor only state changing api -----------
function setPool(address _pool) external;
// ----------- Getters -----------
function nft() external view returns (INonfungiblePositionManager);
function router() external view returns (ISwapRouter);
function pool() external view returns (IUniswapV3Pool);
function tokenId() external view returns (uint256);
function token() external view returns (address);
function liquidityOwned() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "./OracleRef.sol";
import "./IUniRef.sol";
/// @title A Reference to Uniswap
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Uniswap
/// @dev the uniswap v3 pool should be RUSD and another asset
abstract contract UniRef is IUniRef, OracleRef {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
using SafeMathCopy for uint160;
uint256 private constant FIXED_POINT_GRANULARITY = 2**96;
/// @notice the Uniswap V3 position manager
INonfungiblePositionManager public override nft;
/// @notice the Uniswap router contract
ISwapRouter public override router;
/// @notice the referenced Uniswap V3 pool contract
IUniswapV3Pool public override pool;
/// @notice the referenced Uniswap V3 pool position id
uint256 public override tokenId;
/// @notice UniRef constructor
/// @param _core Ring Core to reference
/// @param _pool Uniswap V3 pool to reference
/// @param _nft Uniswap V3 position manager to reference
/// @param _router Uniswap Router to reference
/// @param _oracle oracle to reference
constructor(
address _core,
address _pool,
address _nft,
address _router,
address _oracle
) OracleRef(_core, _oracle) {
_setupPool(_pool);
nft = INonfungiblePositionManager(_nft);
router = ISwapRouter(_router);
_approveTokenToRouter(address(rusd()));
_approveTokenToRouter(token());
_approveTokenToNFT(address(rusd()));
_approveTokenToNFT(token());
}
/// @notice set the new pool contract
/// @param _pool the new pool
/// @dev also approves the router for the new pool token and underlying token
function setPool(address _pool) external override onlyGovernor {
_setupPool(_pool);
_approveTokenToRouter(token());
_approveTokenToNFT(token());
}
/// @notice the address of the non-rusd underlying token
function token() public view override returns (address) {
address token0 = pool.token0();
if (address(rusd()) == token0) {
return pool.token1();
}
return token0;
}
/// @notice amount of pool liquidity owned by this contract
/// @return amount of liquidity
function liquidityOwned() public view override returns (uint128) {
(, , , , , , , uint128 liquidity, , , , ) = nft.positions(tokenId);
return liquidity;
}
/// @notice returns true if price is below the peg
/// @dev counterintuitively checks if peg < price because price is reported as RUSD per X
function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
Decimal.D256 memory price = _getUniswapPrice();
return peg.lessThan(price);
}
/// @notice approves a token for the router
function _approveTokenToRouter(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(router), maxTokens);
}
/// @notice approves a token for the position manager
function _approveTokenToNFT(address _token) internal {
uint256 maxTokens = uint256(-1);
TransferHelper.safeApprove(_token, address(nft), maxTokens);
}
function _setupPool(address _pool) internal {
pool = IUniswapV3Pool(_pool);
emit PoolUpdate(_pool);
}
/// @notice get uniswap price
/// @return price reported as Rusd per X
function _getUniswapPrice()
internal
view
returns (Decimal.D256 memory)
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
if (token() < address(rusd())) {
return Decimal.ratio(sqrtPriceX96, FIXED_POINT_GRANULARITY).pow(2);
} else {
return Decimal.ratio(FIXED_POINT_GRANULARITY, sqrtPriceX96).pow(2);
}
}
/// @notice return current percent distance from peg
/// @dev will return Decimal.zero() if above peg
function _getDistanceToPeg()
internal
view
returns (Decimal.D256 memory distance)
{
Decimal.D256 memory price = _getUniswapPrice();
return _deviationBelowPeg(price, peg());
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function _deviationBelowPeg(
Decimal.D256 memory price,
Decimal.D256 memory peg
) internal pure returns (Decimal.D256 memory) {
// If price <= peg, then RUSD is more expensive and above peg
// In this case we can just return zero for deviation
if (price.lessThanOrEqualTo(peg)) {
return Decimal.zero();
}
Decimal.D256 memory delta = price.sub(peg, "Impossible underflow");
return delta.div(peg);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
library Roots {
// Newton's method https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
function cubeRoot(uint256 y) internal pure returns (uint256 z) {
if (y > 7) {
z = y;
uint256 x = y / 3 + 1;
while (x < z) {
z = x;
x = (y / (x * x) + (2 * x)) / 3;
}
} else if (y != 0) {
z = 1;
}
}
function sqrt(uint256 y) internal pure returns (uint256) {
return Babylonian.sqrt(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Ring Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
// SPDX-License-Identifier: MIT
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);
}
// 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.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information 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 position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
| returns true if price is below the peg counterintuitively checks if peg < price because price is reported as RUSD per X | function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
Decimal.D256 memory price = _getUniswapPrice();
return peg.lessThan(price);
}
| 5,929,666 |
pragma solidity >=0.4.21 <0.7.0;
contract Marketplace {
string public name;
address deployer;
uint public productCount = 0;
mapping(uint => Product) public products;
struct Product {
uint id;
string name;
string description;
string category;
uint rentalDeposit;
uint rentalFee;
address payable owner;
address payable custodian;
uint rentalStart;
bool rented;
}
event ProductCreated(
uint id,
string name,
string description,
string category,
uint rentalDeposit,
uint rentalFee,
address payable owner,
bool rented
);
event ProductRented(
uint id,
string name,
uint rentalDeposit,
uint rentalFee,
address owner,
address custodian,
uint rentalStart,
bool rented
);
event ProductReturned(
uint id,
string name,
uint rentalDeposit,
uint rentalCost,
uint returnedDeposit,
address payable owner,
address payable borrower,
address custodian,
uint rentalDays,
bool rented
);
event ProductDeleted(
uint id,
string name,
address owner,
address custodian,
bool rented
);
event ProductEdited(
uint id,
string name,
string description,
string category,
uint rentalDeposit,
uint rentalFee,
address payable owner,
bool rented
);
constructor() public {
name = "ETHRent Dapp";
deployer = msg.sender;
}
function createProduct(string memory _name, string memory _description, string memory _category, uint _rentalDeposit, uint _rentalFee) public {
// Require a valid name
require(bytes(_name).length > 0);
// Require a valid description
require(bytes(_description).length > 0);
// Require a valid rental deposit
require(_rentalDeposit > 0);
// Require a valid rental fee
require(_rentalFee > 0);
// Increment product count
productCount ++;
// Create the product
products[productCount] = Product(productCount, _name, _description, _category, _rentalDeposit, _rentalFee, msg.sender, msg.sender, 0, false);
// Trigger an event
emit ProductCreated(
productCount,
_name,
_description,
_category,
_rentalDeposit,
_rentalFee,
msg.sender,
false);
}
function rentProduct(uint _id) public payable {
// Fetch the product
Product memory _product = products[_id];
// Fetch the owner
address payable _owner = _product.owner;
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Require that there is enough Ether in the transaction
require(msg.value >= _product.rentalDeposit);
// Require that the product has not been rented already
require(!_product.rented);
// Require that the borrower is not the owner
require(_owner != msg.sender);
// Transfer responsibility to the borrower
_product.custodian = msg.sender;
// Set time when rental starts
_product.rentalStart = now;
// Mark as rented
_product.rented = true;
// Update the product
products[_id] = _product;
// Trigger an event
emit ProductRented(
productCount,
_product.name,
_product.rentalDeposit,
_product.rentalFee,
_product.owner,
msg.sender,
_product.rentalStart,
true);
}
function returnProduct(uint _id, uint _rentalDays) public payable {
// Fetch the product
Product memory _product = products[_id];
// Fetch the owner
address payable _owner = _product.owner;
// Fetch the borrower
address payable _borrower = _product.custodian;
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Require that the product is currently rented
require(_product.rented);
// Require that the borrower is not the owner
require(_owner != _borrower);
// Determine rental period, and associated rental cost
uint endTime;
endTime = now;
uint rentalCost;
rentalCost = _rentalDays * _product.rentalFee;
rentalCost = _product.rentalDeposit <= rentalCost ? _product.rentalDeposit : rentalCost; // x <= y ? x : y
// Transfer responsibility back to owner
_product.custodian = _product.owner;
// Mark as rented
_product.rented = false;
// Update the product
products[_id] = _product;
// Pay the owner by sending them Ether
address(_owner).transfer(rentalCost);
// Return remaining deposit to the borrower
uint returnedDeposit;
returnedDeposit = _product.rentalDeposit - rentalCost;
address(_borrower).transfer(returnedDeposit);
// Trigger an event
emit ProductReturned(
productCount,
_product.name,
_product.rentalDeposit,
rentalCost,
returnedDeposit,
_product.owner,
_borrower,
_product.custodian,
_rentalDays,
_product.rented);
}
function deleteProduct(uint _id) public {
// Fetch the product
Product memory _product = products[_id];
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Make sure only the product owner can delete a product
require(_product.owner == msg.sender);
// Make sure the owner is currently the custodian of the product
require(_product.custodian == _product.owner);
// Mark as rented (i.e. unavailable to rent)
_product.rented = true;
// Update the product
products[_id] = _product;
// Trigger an event
emit ProductDeleted(
productCount,
_product.name,
_product.owner,
_product.custodian,
_product.rented);
}
function editProduct(uint _id, string memory _name, string memory _description, string memory _category, uint _rentalDeposit, uint _rentalFee) public {
// Fetch the product
Product memory _product = products[_id];
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Make sure only the product owner can edit a product
require(_product.owner == msg.sender);
// Make sure the owner is currently the custodian of the product
require(_product.custodian == _product.owner);
// Edit the product
_product.name = _name;
_product.description = _description;
_product.category = _category;
_product.rentalDeposit = _rentalDeposit;
_product.rentalFee = _rentalFee;
products[_id] = _product;
emit ProductEdited(
productCount,
_name,
_description,
_category,
_rentalDeposit,
_rentalFee,
msg.sender,
false);
}
function destroy() public {
// Make sure the function is being called by the contract deployer
require(msg.sender == deployer);
// Remove the contract from the blockchain, return any ether to the deployer
selfdestruct(msg.sender);
}
} | Fetch the product Fetch the owner Fetch the borrower Make sure the product has a valid id Require that the product is currently rented Require that the borrower is not the owner Determine rental period, and associated rental cost Transfer responsibility back to owner Mark as rented Update the product Pay the owner by sending them Ether Return remaining deposit to the borrower Trigger an event | function returnProduct(uint _id, uint _rentalDays) public payable {
Product memory _product = products[_id];
address payable _owner = _product.owner;
address payable _borrower = _product.custodian;
require(_product.id > 0 && _product.id <= productCount);
require(_product.rented);
require(_owner != _borrower);
uint endTime;
endTime = now;
uint rentalCost;
rentalCost = _rentalDays * _product.rentalFee;
_product.custodian = _product.owner;
_product.rented = false;
products[_id] = _product;
address(_owner).transfer(rentalCost);
uint returnedDeposit;
returnedDeposit = _product.rentalDeposit - rentalCost;
address(_borrower).transfer(returnedDeposit);
emit ProductReturned(
productCount,
_product.name,
_product.rentalDeposit,
rentalCost,
returnedDeposit,
_product.owner,
_borrower,
_product.custodian,
_rentalDays,
_product.rented);
}
| 12,936,704 |
./full_match/1/0x0F545C6178830e249117B5162120378735FDD635/sources/contracts/Whitelist.sol | Returns if signer is valid | function _isValidSigner(address signerAddress) internal view returns (bool) {
return _roles[keccak256(abi.encode(signerAddress, ROLE_SIGNER))] == TRUE;
}
| 4,838,199 |
// File: contracts\token\interfaces\IERC20Token.sol
pragma solidity 0.4.26;
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {this;}
function symbol() public view returns (string) {this;}
function decimals() public view returns (uint8) {this;}
function totalSupply() public view returns (uint256) {this;}
function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
// File: contracts\utility\Utils.sol
pragma solidity 0.4.26;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
/**
* constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0, "greaterThanZero");
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0), "validAddress");
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this), "notThis");
_;
}
}
// File: contracts\utility\SafeMath.sol
pragma solidity 0.4.26;
/**
* @dev Library for basic math operations with overflow/underflow protection
*/
library SafeMath {
/**
* @dev returns the sum of _x and _y, reverts if the calculation overflows
*
* @param _x value 1
* @param _y value 2
*
* @return sum
*/
function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
require(z >= _x, "add() z >= _x");
return z;
}
/**
* @dev returns the difference of _x minus _y, reverts if the calculation underflows
*
* @param _x minuend
* @param _y subtrahend
*
* @return difference
*/
function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y, "sub() _x >= _y");
return _x - _y;
}
/**
* @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
*
* @param _x factor 1
* @param _y factor 2
*
* @return product
*/
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
// gas optimization
if (_x == 0)
return 0;
uint256 z = _x * _y;
require(z / _x == _y, "mul() z / _x == _y");
return z;
}
/**
* ev Integer division of two numbers truncating the quotient, reverts on division by zero.
*
* aram _x dividend
* aram _y divisor
*
* eturn quotient
*/
function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_y > 0, "div() _y > 0");
uint256 c = _x / _y;
return c;
}
}
// File: contracts\token\ERC20Token.sol
pragma solidity 0.4.26;
/**
* @dev ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, Utils {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This is for debug purpose
//event Log(address from, string message);
/**
* @dev triggered when tokens are transferred between wallets
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf
*
* @param _owner wallet that approves the allowance
* @param _spender wallet that receives the allowance
* @param _value allowance amount
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This is for debug purpose
event Log(address from, string message);
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _decimals decimal points, for display purposes
* @param _totalSupply total supply of token units
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public {
require(bytes(_name).length > 0 , "constructor: name == 0"); // validate input
require(bytes(_symbol).length > 0, "constructor: symbol == 0"); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceOf[msg.sender] = _totalSupply;
//emit Log(msg.sender, "constractor()");
}
/**
* @dev send coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
//emit Log(msg.sender, "transfer() sender");
return _transfer( msg.sender, _to, _value );
}
/**
* @dev an account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
return _transfer( _from, _to, _value );
}
/**
* @dev allow another account/contract to spend some tokens on your behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
return _approve(msg.sender, _spender, _value );
}
/**
* @dev
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function _transfer(address _from, address _to, uint256 _value)
internal
returns (bool success)
{
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function _approve(address _from, address _spender, uint256 _value)
internal
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[_from][_spender] == 0);
allowance[_from][_spender] = _value;
emit Approval(_from, _spender, _value);
return true;
}
}
// File: contracts\meta_test\TxRelayUtil.sol
pragma solidity 0.4.26;
// -*- coding: utf-8-unix -*-
contract TxRelayUtil {
address txrelay;
modifier onlyTxRelay() {
require(address(0) != txrelay, "TxRelay null");
require(msg.sender == txrelay, "sender not TxRelay");
_;
}
}
// File: contracts\token\CHMToken.sol
pragma solidity 0.4.26;
/**
* @dev ERC20 Standard Token implementation
*/
contract CHMToken is ERC20Token, TxRelayUtil {
/**
* @dev initializes a new ERC20Token instance
*
* @param _name token name
* @param _symbol token symbol
* @param _decimals decimal points, for display purposes
* @param _totalSupply total supply of token units
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public
ERC20Token(_name, _symbol, _decimals, _totalSupply )
{
}
function set_txrelay( address _to ) public
validAddress(_to)
returns (bool success)
{
require(txrelay == address(0), "It has been set txrelay address.");
txrelay = _to;
return true;
}
/**
* @dev
*
* @param _from source address
* @param _to target address
* @param _value transfer amount
*
* @return true if the transfer was successful, false if it wasn't
*/
function transferRelay(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
onlyTxRelay
returns (bool success)
{
//emit Log(msg.sender, "transferRelay() sender");
//emit Log(_from, "transferRelay() from");
//emit Log(_to, "transferRelay() to");
//emit Log(txrelay, "transferRelay() txrelay");
return _transfer( _from, _to, _value );
}
/**
* @dev allow another account/contract to spend some tokens on your behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
* in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
*
* @param _spender approved address
* @param _value allowance amount
*
* @return true if the approval was successful, false if it wasn't
*/
function approveRelay(address _from, address _spender, uint256 _value)
public
validAddress(_from)
validAddress(_spender)
onlyTxRelay
returns (bool success)
{
return _approve(_from, _spender, _value );
}
} | returns the difference of _x minus _y, reverts if the calculation underflows _x minuend _y subtrahend return difference/ | function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y, "sub() _x >= _y");
return _x - _y;
}
| 1,628,683 |
./full_match/421613/0x1C98880c57bCc088b4374cF9c916b6496DAe98d7/sources/src/MintManager/MintManager.sol | allocate claimable amount to user to user address amount usdc amount that user pay for house edge | function allocateXPachi(
address to,
uint256 amount
) external onlyBank notHalt {
uint256 mintAmount = getMintAmount(amount);
claimableAmount[to] += mintAmount;
uint256 price = getPrice();
emit Allocated(to, mintAmount, price, block.timestamp);
}
| 11,572,603 |
pragma solidity ^0.4.13;
import "./Fund.sol";
import "./DataFeed.sol";
import "./zeppelin/DestructibleModified.sol";
import "./math/SafeMath.sol";
/**
* @title InvestorActions
* @author CoinAlpha, Inc. <[email protected]>
*
* @dev This is a supporting module to the Fund contract that performs investor-related actions
* such as subscription, redemption, allocation changes, and withdrawals. By performing checks,
* performing calculations and returning the updated variables to the Fund contract, this module
* may be upgraded after the inception of the Fund contract.
*/
contract IInvestorActions {
function modifyAllocation(address _addr, uint _allocation)
returns (uint _ethTotalAllocation) {}
function getAvailableAllocation(address _addr)
returns (uint ethAvailableAllocation) {}
function requestSubscription(address _addr, uint _amount)
returns (uint, uint) {}
function cancelSubscription(address _addr)
returns (uint, uint, uint, uint) {}
function subscribe(address _addr)
returns (uint, uint, uint, uint, uint, uint) {}
function requestRedemption(address _addr, uint _shares)
returns (uint, uint) {}
function cancelRedemption(address addr)
returns (uint, uint) {}
function redeem(address _addr)
returns (uint, uint, uint, uint, uint, uint, uint) {}
function liquidate(address _addr)
returns (uint, uint, uint, uint, uint, uint) {}
function withdraw(address _addr)
returns (uint, uint, uint) {}
}
contract InvestorActions is DestructibleModified {
using SafeMath for uint;
address public fundAddress;
// Modules
IDataFeed public dataFeed;
IFund fund;
// This modifier is applied to all external methods in this contract since only
// the primary Fund contract can use this module
modifier onlyFund {
require(msg.sender == fundAddress);
_;
}
function InvestorActions(
address _dataFeed
)
{
dataFeed = IDataFeed(_dataFeed);
}
// Modifies the max investment limit allowed for an investor and overwrites the past limit
// Used for both whitelisting a new investor and modifying an existing investor's allocation
function modifyAllocation(address _addr, uint _allocation)
onlyFund
constant
returns (uint _ethTotalAllocation)
{
require(_allocation > 0);
return _allocation;
}
// Get the remaining available amount in Ether that an investor can subscribe for
function getAvailableAllocation(address _addr)
onlyFund
constant
returns (uint ethAvailableAllocation)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
uint ethFilledAllocation = ethPendingSubscription.add(fund.sharesToEth(sharesOwned));
if (ethTotalAllocation > ethFilledAllocation) {
return ethTotalAllocation.sub(ethFilledAllocation);
} else {
return 0;
}
}
// Register an investor's subscription request, after checking that
// 1) the requested amount exceeds the minimum subscription amount and
// 2) the investor's total allocation is not exceeded
function requestSubscription(address _addr, uint _amount)
onlyFund
constant
returns (uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
if (sharesOwned == 0) {
require(_amount >= fund.minInitialSubscriptionEth());
} else {
require(_amount >= fund.minSubscriptionEth());
}
require(ethTotalAllocation >= _amount.add(ethPendingSubscription).add(fund.sharesToEth(sharesOwned)));
return (ethPendingSubscription.add(_amount), // new investor.ethPendingSubscription
fund.totalEthPendingSubscription().add(_amount) // new totalEthPendingSubscription
);
}
// Handles an investor's subscription cancellation, after checking that
// the fund balance has enough ether to cover the withdrawal.
// The amount is then moved from ethPendingSubscription to ethPendingWithdrawal
// so that it can be withdrawn by the investor.
function cancelSubscription(address _addr)
onlyFund
constant
returns (uint, uint, uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
uint otherPendingSubscriptions = fund.totalEthPendingSubscription().sub(ethPendingSubscription);
require(ethPendingSubscription <= fund.balance.sub(fund.totalEthPendingWithdrawal()).sub(otherPendingSubscriptions));
return (0, // new investor.ethPendingSubscription
ethPendingWithdrawal.add(ethPendingSubscription), // new investor.ethPendingWithdrawal
fund.totalEthPendingSubscription().sub(ethPendingSubscription), // new totalEthPendingSubscription
fund.totalEthPendingWithdrawal().add(ethPendingSubscription) // new totalEthPendingWithdrawal
);
}
// Processes an investor's subscription request and mints new shares at the current navPerShare
function subscribe(address _addr)
onlyFund
constant
returns (uint, uint, uint, uint, uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
// Check that the fund balance has enough ether because the Fund contract's subscribe
// function that calls this one will immediately transfer the subscribed amount of ether
// to the exchange account upon function return
uint otherPendingSubscriptions = fund.totalEthPendingSubscription().sub(ethPendingSubscription);
require(ethPendingSubscription <= fund.balance.sub(fund.totalEthPendingWithdrawal()).sub(otherPendingSubscriptions));
uint shares = fund.ethToShares(ethPendingSubscription);
return (0, // new investor.ethPendingSubscription
sharesOwned.add(shares), // new investor.sharesOwned
shares, // shares minted
ethPendingSubscription, // amount transferred to exchange
fund.totalSupply().add(shares), // new totalSupply
fund.totalEthPendingSubscription().sub(ethPendingSubscription) // new totalEthPendingSubscription
);
}
// Register an investor's redemption request, after checking that
// 1) the requested amount exceeds the minimum redemption amount and
// 2) the investor can't redeem more than the shares they own
function requestRedemption(address _addr, uint _shares)
onlyFund
constant
returns (uint, uint)
{
require(_shares >= fund.minRedemptionShares());
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
// Investor's shares owned should be larger than their existing redemption requests
// plus this new redemption request
require(sharesOwned >= _shares.add(sharesPendingRedemption));
return (sharesPendingRedemption.add(_shares), // new investor.sharesPendingRedemption
fund.totalSharesPendingRedemption().add(_shares) // new totalSharesPendingRedemption
);
}
// Handles an investor's redemption cancellation, after checking that
// the fund balance has enough ether to cover the withdrawal.
// The amount is then moved from sharesPendingRedemption
function cancelRedemption(address addr)
onlyFund
constant
returns (uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(addr);
// Check that the total shares pending redemption is greator than the investor's shares pending redemption
assert(fund.totalSharesPendingRedemption() >= sharesPendingRedemption);
return (0, // new investor.sharesPendingRedemption
fund.totalSharesPendingRedemption().sub(sharesPendingRedemption) // new totalSharesPendingRedemption
);
}
// Processes an investor's redemption request and annilates their shares at the current navPerShare
function redeem(address _addr)
onlyFund
constant
returns (uint, uint, uint, uint, uint, uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
// Check that the fund balance has enough ether because after this function is processed, the ether
// equivalent amount can be withdrawn by the investor
uint amount = fund.sharesToEth(sharesPendingRedemption);
require(amount <= fund.balance.sub(fund.totalEthPendingSubscription()).sub(fund.totalEthPendingWithdrawal()));
return (sharesOwned.sub(sharesPendingRedemption), // new investor.sharesOwned
0, // new investor.sharesPendingRedemption
ethPendingWithdrawal.add(amount), // new investor.ethPendingWithdrawal
sharesPendingRedemption, // shares annihilated
fund.totalSupply().sub(sharesPendingRedemption), // new totalSupply
fund.totalSharesPendingRedemption().sub(sharesPendingRedemption), // new totalSharesPendingRedemption
fund.totalEthPendingWithdrawal().add(amount) // new totalEthPendingWithdrawal
);
}
// Converts all of an investor's shares to ether and makes it available for withdrawal. Also makes the investor's allocation zero to prevent future investment.
function liquidate(address _addr)
onlyFund
constant
returns (uint, uint, uint, uint, uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
// Check that the fund balance has enough ether because after this function is processed, the ether
// equivalent amount can be withdrawn by the investor. The fund balance less total withdrawals and other
// investors' pending subscriptions should be larger than or equal to the liquidated amount.
uint otherPendingSubscriptions = fund.totalEthPendingSubscription().sub(ethPendingSubscription);
uint amount = fund.sharesToEth(sharesOwned).add(ethPendingSubscription);
require(amount <= fund.balance.sub(fund.totalEthPendingWithdrawal()).sub(otherPendingSubscriptions));
return (ethPendingWithdrawal.add(amount), // new investor.ethPendingWithdrawal
sharesOwned, // shares annihilated
fund.totalEthPendingSubscription().sub(ethPendingSubscription), // new totalEthPendingSubscription
fund.totalSharesPendingRedemption().sub(sharesPendingRedemption), // new totalSharesPendingRedemption
fund.totalSupply().sub(sharesOwned), // new totalSupply
fund.totalEthPendingWithdrawal().add(amount) // new totalEthPendingWithdrawal
);
}
// Handles a withdrawal by an investor
function withdraw(address _addr)
onlyFund
constant
returns (uint, uint, uint)
{
var (ethTotalAllocation, ethPendingSubscription, sharesOwned, sharesPendingRedemption, ethPendingWithdrawal) = fund.getInvestor(_addr);
// Check that the fund balance has enough ether to cover the withdrawal after subtracting pending subscriptions
// and other investors' withdrawals
require(ethPendingWithdrawal != 0);
uint otherInvestorPayments = fund.totalEthPendingWithdrawal().sub(ethPendingWithdrawal);
require(ethPendingWithdrawal <= fund.balance.sub(fund.totalEthPendingSubscription()).sub(otherInvestorPayments));
return (ethPendingWithdrawal, // payment to be sent
0, // new investor.ethPendingWithdrawal
fund.totalEthPendingWithdrawal().sub(ethPendingWithdrawal) // new totalEthPendingWithdrawal
);
}
// ********* ADMIN *********
// Update the address of the Fund contract
function setFund(address _fund)
onlyOwner
returns (bool success)
{
fund = IFund(_fund);
fundAddress = _fund;
return true;
}
// Update the address of the data feed contract
function setDataFeed(address _address)
onlyOwner
returns (bool success)
{
dataFeed = IDataFeed(_address);
return true;
}
}
| Update the address of the data feed contract | function setDataFeed(address _address)
onlyOwner
returns (bool success)
{
dataFeed = IDataFeed(_address);
return true;
}
| 12,924,309 |
./full_match/11155111/0x2d43c99479F4e5aE23fB930a3350D44b6a632CAa/sources/contracts/manifold/libraries-solidity/access/UserControl.sol | See {IAdminControl-approveUser}./ | function approveUser(address user) external override {
require(
IAdminControl(address(this)).isAdmin(msg.sender),
"AdminControl: Must be owner or admin"
);
if (!_users.contains(user)) {
emit UserApproved(user, msg.sender);
_users.add(user);
}
}
| 3,836,041 |
pragma solidity ^0.4.11;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
// ----------------------------------------------------------------------------------------------
// Original from:
// https://theethereum.wiki/w/index.php/ERC20_Token_Standard
// (c) BokkyPooBah 2017. The MIT Licence.
// ----------------------------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
contract ERC20Interface {
// Get the total token supply function totalSupply() constant returns (uint256 totalSupply);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Send _value amount of token from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address _spender, uint256 _value) returns (bool success);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// Migration Agent interface
contract migration {
function migrateFrom(address _from, uint256 _value);
}
/// @title Zeus Shield Coin (ZSC)
contract ZeusShieldCoin is owned, ERC20Interface {
// Public variables of the token
string public constant standard = 'ERC20';
string public constant name = 'Zeus Shield Coin';
string public constant symbol = 'ZSC';
uint8 public constant decimals = 18;
uint public registrationTime = 0;
bool public registered = false;
uint256 public totalMigrated = 0;
address public migrationAgent = 0;
uint256 totalTokens = 0;
// This creates an array with all balances
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// These are related to ZSC team members
mapping (address => bool) public frozenAccount;
mapping (address => uint[3]) public frozenTokens;
// Variables of token frozen rules for ZSC team members.
uint[3] public unlockat;
event Migrate(address _from, address _to, uint256 _value);
// Constructor
function ZeusShieldCoin()
{
}
// This unnamed function is called whenever someone tries to send ether to it
function ()
{
throw; // Prevents accidental sending of ether
}
function totalSupply()
constant
returns (uint256)
{
return totalTokens;
}
// What is the balance of a particular account?
function balanceOf(address _owner)
constant
returns (uint256)
{
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount)
returns (bool success)
{
if (!registered) return false;
if (_amount <= 0) return false;
if (frozenRules(msg.sender, _amount)) return false;
if (balances[msg.sender] >= _amount
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _amount)
returns (bool success)
{
if (!registered) return false;
if (_amount <= 0) return false;
if (frozenRules(_from, _amount)) return false;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount)
returns (bool success)
{
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender)
constant
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/// @dev Set address of migration agent contract and enable migration
/// @param _agent The address of the MigrationAgent contract
function setMigrationAgent(address _agent)
public
onlyOwner
{
if (!registered) throw;
if (migrationAgent != 0) throw;
migrationAgent = _agent;
}
/// @dev Buyer can apply for migrating tokens to the new token contract.
/// @param _value The amount of token to be migrated
function applyMigrate(uint256 _value)
public
{
if (!registered) throw;
if (migrationAgent == 0) throw;
// Validate input value.
if (_value == 0) throw;
if (_value > balances[msg.sender]) throw;
balances[msg.sender] -= _value;
totalTokens -= _value;
totalMigrated += _value;
migration(migrationAgent).migrateFrom(msg.sender, _value);
Migrate(msg.sender, migrationAgent, _value);
}
/// @dev Register for crowdsale and do the token pre-allocation.
/// @param _tokenFactory The address of ICO-sale contract
/// @param _congressAddress The address of multisig token contract
function registerSale(address _tokenFactory, address _congressAddress)
public
onlyOwner
{
// The token contract can be only registered once.
if (!registered) {
// Total supply
totalTokens = 6100 * 1000 * 1000 * 10**18;
// (51%) of total supply to ico-sale contract
balances[_tokenFactory] = 3111 * 1000 * 1000 * 10**18;
// (34%) of total supply to the congress address for congress and partners
balances[_congressAddress] = 2074 * 1000 * 1000 * 10**18;
// Allocate rest (15%) of total supply to development team and contributors
// 915,000,000 * 10**18;
teamAllocation();
registered = true;
registrationTime = now;
unlockat[0] = registrationTime + 6 * 30 days;
unlockat[1] = registrationTime + 12 * 30 days;
unlockat[2] = registrationTime + 24 * 30 days;
}
}
/// @dev Allocate 15% of total supply to ten team members.
/// @param _account The address of account to be frozen.
/// @param _totalAmount The amount of tokens to be frozen.
function freeze(address _account, uint _totalAmount)
public
onlyOwner
{
frozenAccount[_account] = true;
frozenTokens[_account][0] = _totalAmount; // 100% of locked token within 6 months
frozenTokens[_account][1] = _totalAmount * 80 / 100; // 80% of locked token within 12 months
frozenTokens[_account][2] = _totalAmount * 50 / 100; // 50% of locked token within 24 months
}
/// @dev Allocate 15% of total supply to the team members.
function teamAllocation()
internal
{
// 1.5% of total supply allocated to each team member.
uint individual = 91500 * 1000 * 10**18;
balances[0xCDc5BDEFC6Fddc66E73250fCc2F08339e091dDA3] = individual; // 1.5%
balances[0x8b47D27b085a661E6306Ac27A932a8c0b1C11b84] = individual; // 1.5%
balances[0x825f4977DB4cd48aFa51f8c2c9807Ee89120daB7] = individual; // 1.5%
balances[0xcDf5D7049e61b2F50642DF4cb5a005b1b4A5cfc2] = individual; // 1.5%
balances[0xab0461FB41326a960d3a2Fe2328DD9A65916181d] = individual; // 1.5%
balances[0xd2A131F16e4339B2523ca90431322f559ABC4C3d] = individual; // 1.5%
balances[0xCcB4d663E6b05AAda0e373e382628B9214932Fff] = individual; // 1.5%
balances[0x60284720542Ff343afCA6a6DBc542901942260f2] = individual; // 1.5%
balances[0xcb6d0e199081A489f45c73D1D22F6de58596a99C] = individual; // 1.5%
balances[0x928D99333C57D31DB917B4c67D4d8a033F2143A7] = individual; // 1.5%
// Freeze tokens allocated to the team for at most two years.
// Freeze tokens in three phases
// 91500 * 1000 * 10**18; 100% of locked tokens within 6 months
// 73200 * 1000 * 10**18; 80% of locked tokens within 12 months
// 45750 * 1000 * 10**18; 50% of locked tokens within 24 months
freeze("0xCDc5BDEFC6Fddc66E73250fCc2F08339e091dDA3", individual);
freeze("0x8b47D27b085a661E6306Ac27A932a8c0b1C11b84", individual);
freeze("0x825f4977DB4cd48aFa51f8c2c9807Ee89120daB7", individual);
freeze("0xcDf5D7049e61b2F50642DF4cb5a005b1b4A5cfc2", individual);
freeze("0xab0461FB41326a960d3a2Fe2328DD9A65916181d", individual);
freeze("0xd2A131F16e4339B2523ca90431322f559ABC4C3d", individual);
freeze("0xCcB4d663E6b05AAda0e373e382628B9214932Fff", individual);
freeze("0x60284720542Ff343afCA6a6DBc542901942260f2", individual);
freeze("0xcb6d0e199081A489f45c73D1D22F6de58596a99C", individual);
freeze("0x928D99333C57D31DB917B4c67D4d8a033F2143A7", individual);
}
/// @dev Token frozen rules for token holders.
/// @param _from The token sender.
/// @param _value The token amount.
function frozenRules(address _from, uint256 _value)
internal
returns (bool success)
{
if (frozenAccount[_from]) {
if (now < unlockat[0]) {
// 100% locked within the first 6 months.
if (balances[_from] - _value < frozenTokens[_from][0])
return true;
} else if (now >= unlockat[0] && now < unlockat[1]) {
// 20% unlocked after 6 months.
if (balances[_from] - _value < frozenTokens[_from][1])
return true;
} else if (now >= unlockat[1] && now < unlockat[2]) {
// 50% unlocked after 12 months.
if (balances[_from]- _value < frozenTokens[_from][2])
return true;
} else {
// 100% unlocked after 24 months.
frozenAccount[_from] = false;
}
}
return false;
}
}
| Allocate 15% of total supply to the team members. 1.5% of total supply allocated to each team member. Freeze tokens allocated to the team for at most two years. Freeze tokens in three phases 91500 1000 1018; 100% of locked tokens within 6 months 73200 1000 1018; 80% of locked tokens within 12 months 45750 1000 1018; 50% of locked tokens within 24 months | function teamAllocation()
internal
{
uint individual = 91500 * 1000 * 10**18;
freeze("0xCDc5BDEFC6Fddc66E73250fCc2F08339e091dDA3", individual);
freeze("0x8b47D27b085a661E6306Ac27A932a8c0b1C11b84", individual);
freeze("0x825f4977DB4cd48aFa51f8c2c9807Ee89120daB7", individual);
freeze("0xcDf5D7049e61b2F50642DF4cb5a005b1b4A5cfc2", individual);
freeze("0xab0461FB41326a960d3a2Fe2328DD9A65916181d", individual);
freeze("0xd2A131F16e4339B2523ca90431322f559ABC4C3d", individual);
freeze("0xCcB4d663E6b05AAda0e373e382628B9214932Fff", individual);
freeze("0x60284720542Ff343afCA6a6DBc542901942260f2", individual);
freeze("0xcb6d0e199081A489f45c73D1D22F6de58596a99C", individual);
freeze("0x928D99333C57D31DB917B4c67D4d8a033F2143A7", individual);
}
| 13,140,267 |
./partial_match/42/0x4995e3D49e00C0c6058B1bC749904311D08B8f24/sources/StakeTops.sol | 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./ 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('')` solhint-disable-next-line no-inline-assembly | function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
| 3,389,004 |
/*
This file is part of The Colony Network.
The Colony Network 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.
The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
pragma experimental "v0.5.0";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
// TODO: Can we handle all possible disputes regarding the very first hash that should be set?
// Currently, at the very least, we can't handle a dispute if the very first entry is disputed.
// A possible workaround would be to 'kick off' reputation mining with a known dummy state...
contract ReputationMiningCycle is PatriciaTreeProofs, DSMath {
ReputationLogEntry[] reputationUpdateLog;
struct ReputationLogEntry {
address user;
int amount;
uint256 skillId;
address colony;
uint256 nUpdates;
uint256 nPreviousUpdates;
}
address colonyNetworkAddress;
// TODO: Do we need both these mappings?
mapping (bytes32 => mapping( uint256 => address[])) public submittedHashes;
mapping (address => Submission) public reputationHashSubmissions;
uint256 public reputationMiningWindowOpenTimestamp;
mapping (uint256 => Submission[]) public disputeRounds;
// Tracks the number of submissions in each round that have completed their challenge, one way or the other.
// This might be that they passed the challenge, it might be that their opponent passed (and therefore by implication,
// they failed), or it might be that they timed out
mapping (uint256 => uint256) nHashesCompletedChallengeRound;
// A flaw with this is that if someone spams lots of nonsense transactions, then 'good' users still have to come along and
// explicitly complete the pairings. But if they get the tokens that were staked in order to make the submission, maybe
// that's okay...?
// Number of unique hashes submitted
uint256 public nSubmittedHashes = 0;
uint256 public nInvalidatedHashes = 0;
struct Submission {
bytes32 proposedNewRootHash; // The hash that the submitter is proposing as the next reputation hash
uint256 nNodes; // The number of nodes in the reputation tree being proposed as the next reputation hash
uint256 lastResponseTimestamp; // If nonzero, the last time that a valid response was received corresponding to this
// submission during the challenge process - either binary searching for the challenge,
// responding to the challenge itself or submitting the JRH
uint256 challengeStepCompleted; // How many valid responses have been received corresponding to this submission during
// the challenge process.
bytes32 jrh; // The Justification Root Hash corresponding to this submission.
bytes32 intermediateReputationHash; // The hash this submission hash has as a leaf node in the tree the JRH is the root of where
// this submission and its opponent differ for the first time.
uint256 intermediateReputationNNodes; // The number of nodes in the reputation tree in the reputation state where this submission and
// its opponent first differ.
uint256 jrhNnodes; // The number of nodes in the tree the JRH is the root of.
uint256 lowerBound; // During the binary search, the lowest index in the justification tree that might still be the
// first place where the two submissions differ.
uint256 upperBound; // During the binary search, the highest index in the justification tree that might still be the
// first place where the two submissions differ.
// When the binary search is complete, lowerBound and upperBound are equal
uint256 provedPreviousReputationUID; // If the disagreement between this submission and its opponent is related to the insertion of a
// new leaf, the submitters also submit proof of a reputation in a state that the two agree on. The
// UID that reputation has is stored here, and whichever submission proves the higher existing UID is
// deemed correct, assuming it also matches the UID for the new reputation being inserted.
}
// Records for which hashes, for which addresses, for which entries have been accepted
// Otherwise, people could keep submitting the same entry.
mapping (bytes32 => mapping(address => mapping(uint256 => bool))) submittedEntries;
/// @notice A modifier that checks that the supplied `roundNumber` is the final round
/// @param roundNumber The `roundNumber` to check if it is the final round
modifier finalDisputeRoundCompleted(uint roundNumber) {
require (nSubmittedHashes - nInvalidatedHashes == 1);
require (disputeRounds[roundNumber].length == 1); //i.e. this is the final round
// Note that even if we are passed the penultimate round, which had a length of two, and had one eliminated,
// and therefore 'delete' called in `invalidateHash`, the array still has a length of '2' - it's just that one
// element is zeroed. If this functionality of 'delete' is ever changed, this will have to change too.
_;
}
/// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open
/// @param round The round number of the hash under consideration
/// @param idx The index in the round of the hash under consideration
modifier challengeOpen(uint256 round, uint256 idx) {
// TODO: More checks that this is an appropriate time to respondToChallenge
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound);
_;
}
/// @notice A modifier that checks if the proposed entry is eligible. The more CLNY a user stakes, the more
/// potential entries they have in a reputation mining cycle. This is effectively restricting the nonce range
/// that is allowable from a given user when searching for a submission that will pass `withinTarget`. A user
/// is allowed to use multiple entries in a single cycle, but each entry can only be used once per cycle, and
/// if there are multiple entries they must all be for the same proposed Reputation State Root Hash with the
/// same number of nodes.
/// @param newHash The hash being submitted
/// @param nNodes The number of nodes in the reputation tree that `newHash` is the root hash of
/// @param entryIndex The number of the entry the submitter hash asked us to consider.
modifier entryQualifies(bytes32 newHash, uint256 nNodes, uint256 entryIndex) {
// TODO: Require minimum stake, that is (much) more than the cost required to defend the valid submission.
// Here, the minimum stake is 10**15.
require(entryIndex <= IColonyNetwork(colonyNetworkAddress).getStakedBalance(msg.sender) / 10**15);
require(entryIndex > 0);
if (reputationHashSubmissions[msg.sender].proposedNewRootHash != 0x0) { // If this user has submitted before during this round...
require(newHash == reputationHashSubmissions[msg.sender].proposedNewRootHash); // ...require that they are submitting the same hash ...
require(nNodes == reputationHashSubmissions[msg.sender].nNodes); // ...require that they are submitting the same number of nodes for that hash ...
require (submittedEntries[newHash][msg.sender][entryIndex] == false); // ... but not this exact entry
}
_;
}
/// @notice A modifier that checks if the proposed entry is within the current allowable submission window
/// @dev A submission will only be accepted from a reputation miner if `keccak256(address, N, hash) < target`
/// At the beginning of the submission window, the target is set to 0 and slowly increases to 2^256 - 1 after an hour
modifier withinTarget(bytes32 newHash, uint256 entryIndex) {
require(reputationMiningWindowOpenTimestamp > 0);
// Check the ticket is a winning one.
// TODO Figure out how to uncomment the next line, but not break tests sporadically.
// require((now-reputationMiningWindowOpenTimestamp) <= 3600);
// x = floor(uint((2**256 - 1) / 3600)
if (now - reputationMiningWindowOpenTimestamp <= 3600) {
uint256 x = 32164469232587832062103051391302196625908329073789045566515995557753647122;
uint256 target = (now - reputationMiningWindowOpenTimestamp ) * x;
require(uint256(getEntryHash(msg.sender, entryIndex, newHash)) < target);
}
_;
}
function getEntryHash(address submitter, uint256 entryIndex, bytes32 newHash) public pure returns (bytes32) {
return keccak256(abi.encodePacked(submitter, entryIndex, newHash));
}
/// @notice Constructor for this contract.
constructor() public {
colonyNetworkAddress = msg.sender;
}
function resetWindow() public {
require(msg.sender == colonyNetworkAddress);
reputationMiningWindowOpenTimestamp = now;
}
function submitRootHash(bytes32 newHash, uint256 nNodes, uint256 entryIndex)
entryQualifies(newHash, nNodes, entryIndex)
withinTarget(newHash, entryIndex)
public
{
// Limit the total number of miners allowed to submit a specific hash to 12
require (submittedHashes[newHash][nNodes].length < 12);
// If this is a new hash, increment nSubmittedHashes as such.
if (submittedHashes[newHash][nNodes].length == 0) {
nSubmittedHashes += 1;
// And add it to the first disputeRound
// NB if no other hash is submitted, no dispute resolution will be required.
disputeRounds[0].push(Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
}));
// If we've got a pair of submissions to face off, may as well start now.
if (nSubmittedHashes % 2 == 0) {
disputeRounds[0][nSubmittedHashes-1].lastResponseTimestamp = now;
disputeRounds[0][nSubmittedHashes-2].lastResponseTimestamp = now;
/* disputeRounds[0][nSubmittedHashes-1].upperBound = disputeRounds[0][nSubmittedHashes-1].jrhNnodes; */
/* disputeRounds[0][nSubmittedHashes-2].upperBound = disputeRounds[0][nSubmittedHashes-2].jrhNnodes; */
}
}
reputationHashSubmissions[msg.sender] = Submission({
proposedNewRootHash: newHash,
jrh: 0x0,
nNodes: nNodes,
lastResponseTimestamp: 0,
challengeStepCompleted: 0,
lowerBound: 0,
upperBound: 0,
jrhNnodes: 0,
intermediateReputationHash: 0x0,
intermediateReputationNNodes: 0,
provedPreviousReputationUID: 0
});
// And add the miner to the array list of submissions here
submittedHashes[newHash][nNodes].push(msg.sender);
// Note that they submitted it.
submittedEntries[newHash][msg.sender][entryIndex] = true;
}
function confirmNewHash(uint256 roundNumber) public
finalDisputeRoundCompleted(roundNumber)
{
// TODO: Require some amount of time to have passed (i.e. people have had a chance to submit other hashes)
Submission storage submission = disputeRounds[roundNumber][0];
IColonyNetwork(colonyNetworkAddress).setReputationRootHash(submission.proposedNewRootHash, submission.nNodes, submittedHashes[submission.proposedNewRootHash][submission.nNodes]);
selfdestruct(colonyNetworkAddress);
}
function invalidateHash(uint256 round, uint256 idx) public {
// What we do depends on our opponent, so work out which index it was at in disputeRounds[round]
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
uint256 nInNextRound;
// We require either
// 1. That we actually had an opponent - can't invalidate the last hash.
// 2. This cycle had an odd number of submissions, which was larger than 1, and we're giving the last entry a bye to the next round.
if (disputeRounds[round].length % 2 == 1 && disputeRounds[round].length == idx) {
// This is option two above - note that because arrays are zero-indexed, if idx==length, then
// this is the slot after the last entry, and so our opponentIdx will be the last entry
// We just move the opponent on, and nothing else happens.
// Ensure that the previous round is complete, and this entry wouldn't possibly get an opponent later on.
require(nHashesCompletedChallengeRound[round-1] == disputeRounds[round-1].length);
// Prevent us invalidating the final hash
require(disputeRounds[round].length > 1);
// Move opponent on to next round
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// Note the fact that this round has had another challenge complete
nHashesCompletedChallengeRound[round] += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
require(disputeRounds[round].length > opponentIdx);
require(disputeRounds[round][opponentIdx].proposedNewRootHash != "");
// Require that this is not better than its opponent.
require(disputeRounds[round][opponentIdx].challengeStepCompleted >= disputeRounds[round][idx].challengeStepCompleted);
require(disputeRounds[round][opponentIdx].provedPreviousReputationUID >= disputeRounds[round][idx].provedPreviousReputationUID);
// Require that it has failed a challenge (i.e. failed to respond in time)
require(now - disputeRounds[round][idx].lastResponseTimestamp >= 600); //'In time' is ten minutes here.
// Work out whether we are invalidating just the supplied idx or its opponent too.
bool eliminateOpponent = false;
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted &&
disputeRounds[round][opponentIdx].provedPreviousReputationUID == disputeRounds[round][idx].provedPreviousReputationUID) {
eliminateOpponent = true;
}
if (!eliminateOpponent) {
// If here, then the opponent completed one more challenge round than the submission being invalidated or
// proved a later UID was in the tree, so we don't know if they're valid or not yet. Move them on to the next round.
disputeRounds[round+1].push(disputeRounds[round][opponentIdx]);
delete disputeRounds[round][opponentIdx];
// TODO Delete the hash(es) being invalidated?
nInvalidatedHashes += 1;
// Check if the hash we just moved to the next round is the second of a pairing that should now face off.
nInNextRound = disputeRounds[round+1].length;
if (nInNextRound % 2 == 0) {
startPairingInRound(round+1);
}
} else {
// Our opponent completed the same number of challenge rounds, and both have now timed out.
nInvalidatedHashes += 2;
// Punish the people who proposed our opponent
IColonyNetwork(colonyNetworkAddress).punishStakers(submittedHashes[disputeRounds[round][opponentIdx].proposedNewRootHash][disputeRounds[round][opponentIdx].nNodes]);
}
// Note that two hashes have completed this challenge round (either one accepted for now and one rejected, or two rejected)
nHashesCompletedChallengeRound[round] += 2;
// Punish the people who proposed the hash that was rejected
IColonyNetwork(colonyNetworkAddress).punishStakers(submittedHashes[disputeRounds[round][idx].proposedNewRootHash][disputeRounds[round][idx].nNodes]);
}
//TODO: Can we do some deleting to make calling this as cheap as possible for people?
}
function respondToBinarySearchForChallenge(uint256 round, uint256 idx, bytes jhIntermediateValue, uint branchMask, bytes32[] siblings) public {
// TODO: Check this challenge is active.
// This require is necessary, but not a sufficient check (need to check we have an opponent, at least).
require(disputeRounds[round][idx].lowerBound!=disputeRounds[round][idx].upperBound);
uint256 targetNode = add(disputeRounds[round][idx].lowerBound, sub(disputeRounds[round][idx].upperBound, disputeRounds[round][idx].lowerBound) / 2);
bytes32 jrh = disputeRounds[round][idx].jrh;
bytes memory targetNodeBytes = new bytes(32);
assembly {
mstore(add(targetNodeBytes, 0x20), targetNode)
}
bytes32 impliedRoot = getImpliedRoot(targetNodeBytes, jhIntermediateValue, branchMask, siblings);
require(impliedRoot==jrh, "colony-invalid-binary-search-response");
// If require hasn't thrown, proof is correct.
// Process the consequences
processBinaryChallengeSearchResponse(round, idx, jhIntermediateValue, targetNode);
}
uint constant U_ROUND = 0;
uint constant U_IDX = 1;
uint constant U_REPUTATION_BRANCH_MASK = 2;
uint constant U_AGREE_STATE_NNODES = 3;
uint constant U_AGREE_STATE_BRANCH_MASK = 4;
uint constant U_DISAGREE_STATE_NNODES = 5;
uint constant U_DISAGREE_STATE_BRANCH_MASK = 6;
uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7;
uint constant U_REQUIRE_REPUTATION_CHECK = 8;
function respondToChallenge(
uint256[9] u, //An array of 9 UINT Params, ordered as given above.
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings,
bytes disagreeStateReputationValue,
bytes32[] disagreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings
) public
challengeOpen(u[U_ROUND], u[U_IDX])
{
u[U_REQUIRE_REPUTATION_CHECK] = 0;
// TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier);
/* bytes32 jrh = disputeRounds[round][idx].jrh; */
// The contract knows
// 1. the jrh for this submission
// 2. The first index where this submission and its opponent differ.
// Need to prove
// 1. The reputation that is updated that we disagree on's value, before the first index
// where we differ, and in the first index where we differ.
// 2. That no other changes are made to the reputation state. The proof for those
// two reputations in (1) is therefore required to be the same.
// 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps
// after looking up the corresponding entry in the reputation update log (the alternative is
// that it's a decay calculation - not yet implemented.)
// Check the supplied key is appropriate.
checkKey(u[U_ROUND], u[U_IDX], _reputationKey);
// Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH
proveBeforeReputationValue(u, _reputationKey, reputationSiblings, agreeStateReputationValue, agreeStateSiblings);
// Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners)
// By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in.
proveAfterReputationValue(u, _reputationKey, reputationSiblings, disagreeStateReputationValue, disagreeStateSiblings);
// Perform the reputation calculation ourselves.
performReputationCalculation(u, agreeStateReputationValue, disagreeStateReputationValue, previousNewReputationValue);
// If necessary, check the supplied previousNewRepuation is, in fact, in the same reputation state as the agreeState
if (u[U_REQUIRE_REPUTATION_CHECK]==1) {
checkPreviousReputationInState(
u,
_reputationKey,
reputationSiblings,
agreeStateReputationValue,
agreeStateSiblings,
previousNewReputationKey,
previousNewReputationValue,
previousNewReputationSiblings);
saveProvedReputation(u, previousNewReputationValue);
}
// If everthing checked out, note that we've responded to the challenge.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
// Safety net?
/* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){
// Freeze the reputation mining system.
} */
}
function submitJustificationRootHash(
uint256 round,
uint256 index,
bytes32 jrh,
uint branchMask1,
bytes32[] siblings1,
uint branchMask2,
bytes32[] siblings2
) public
{
// Require we've not submitted already.
require(disputeRounds[round][index].jrh == 0x0);
// Check the proofs for the JRH
checkJRHProof1(jrh, branchMask1, siblings1);
checkJRHProof2(round, index, jrh, branchMask2, siblings2);
// Store their JRH
disputeRounds[round][index].jrh = jrh;
disputeRounds[round][index].lastResponseTimestamp = now;
disputeRounds[round][index].challengeStepCompleted += 1;
// Set bounds for first binary search if it's going to be needed
disputeRounds[round][index].upperBound = disputeRounds[round][index].jrhNnodes;
}
function appendReputationUpdateLog(address _user, int _amount, uint _skillId, address _colonyAddress, uint _nParents, uint _nChildren) public {
require(colonyNetworkAddress == msg.sender);
uint reputationUpdateLogLength = reputationUpdateLog.length;
uint nPreviousUpdates = 0;
if (reputationUpdateLogLength > 0) {
nPreviousUpdates = reputationUpdateLog[reputationUpdateLogLength-1].nPreviousUpdates + reputationUpdateLog[reputationUpdateLogLength-1].nUpdates;
}
uint nUpdates = (_nParents + 1) * 2;
if (_amount < 0) {
//TODO: Never true currently. _amount needs to be an int.
nUpdates += 2 * _nChildren;
}
reputationUpdateLog.push(ReputationLogEntry(
_user,
_amount,
_skillId,
_colonyAddress,
nUpdates,
nPreviousUpdates));
}
function getReputationUpdateLogLength() public view returns (uint) {
return reputationUpdateLog.length;
}
function getReputationUpdateLogEntry(uint256 _id) public view returns (address, int256, uint256, address, uint256, uint256) {
ReputationLogEntry storage x = reputationUpdateLog[_id];
return (x.user, x.amount, x.skillId, x.colony, x.nUpdates, x.nPreviousUpdates);
}
function rewardStakersWithReputation(address[] stakers, address commonColonyAddress, uint reward) public {
require(reputationUpdateLog.length==0);
require(msg.sender == colonyNetworkAddress);
for (uint256 i = 0; i < stakers.length; i++) {
// We *know* we're the first entries in this reputation update log, so we don't need all the bookkeeping in
// the AppendReputationUpdateLog function
reputationUpdateLog.push(ReputationLogEntry(
stakers[i],
int256(reward),
0, //TODO: Work out what skill this should be. This should be a special 'mining' skill.
commonColonyAddress, // They earn this reputation in the common colony.
4, // Updates the user's skill, and the colony's skill, both globally and for the special 'mining' skill
i*4 //We're zero indexed, so this is the number of updates that came before in the reputation log.
));
}
}
/////////////////////////
// Internal functions
/////////////////////////
function processBinaryChallengeSearchResponse(uint256 round, uint256 idx, bytes jhIntermediateValue, uint256 targetNode) internal {
disputeRounds[round][idx].lastResponseTimestamp = now;
disputeRounds[round][idx].challengeStepCompleted += 1;
// Save our intermediate hash
bytes32 intermediateReputationHash;
uint256 intermediateReputationNNodes;
assembly {
intermediateReputationHash := mload(add(jhIntermediateValue, 0x20))
intermediateReputationNNodes := mload(add(jhIntermediateValue, 0x40))
}
disputeRounds[round][idx].intermediateReputationHash = intermediateReputationHash;
disputeRounds[round][idx].intermediateReputationNNodes = intermediateReputationNNodes;
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted ) {
// Our opponent answered this challenge already.
// Compare our intermediateReputationHash to theirs to establish how to move the bounds.
processBinaryChallengeSearchStep(round, idx, targetNode);
}
}
function processBinaryChallengeSearchStep(uint256 round, uint256 idx, uint256 targetNode) internal {
uint256 opponentIdx = (idx % 2 == 1 ? idx-1 : idx + 1);
if (
disputeRounds[round][opponentIdx].intermediateReputationHash == disputeRounds[round][idx].intermediateReputationHash &&
disputeRounds[round][opponentIdx].intermediateReputationNNodes == disputeRounds[round][idx].intermediateReputationNNodes
)
{
disputeRounds[round][idx].lowerBound = targetNode + 1;
disputeRounds[round][opponentIdx].lowerBound = targetNode + 1;
} else {
// NB no '-1' to mirror the '+1' above in the other bound, because
// we're looking for the first index where these two submissions differ
// in their calculations - they disagreed for this index, so this might
// be the first index they disagree about
disputeRounds[round][idx].upperBound = targetNode;
disputeRounds[round][opponentIdx].upperBound = targetNode;
}
// We need to keep the intermediate hashes so that we can figure out what type of dispute we are resolving later
// If the number of nodes in the reputation state are different, then we are disagreeing on whether this log entry
// corresponds to an existing reputation entry or not.
// If the hashes are different, then it's a calculation error.
// Our opponent responded to this step of the challenge before we did, so we should
// reset their 'last response' time to now, as they aren't able to respond
// to the next challenge before they know what it is!
disputeRounds[round][opponentIdx].lastResponseTimestamp = now;
}
function checkKey( uint256 round, uint256 idx, bytes memory _reputationKey) internal {
// If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition (TODO: not implemented)
// Otherwise, look up the corresponding entry in the reputation log.
uint256 updateNumber = disputeRounds[round][idx].lowerBound - 1;
bytes memory reputationKey = new bytes(20+32+20);
reputationKey = _reputationKey;
address colonyAddress;
address userAddress;
uint256 skillId;
assembly {
colonyAddress := mload(add(reputationKey,20)) // 20, not 32, because we're copying in to a slot that will be interpreted as an address.
// which will truncate the leftmost 12 bytes
skillId := mload(add(reputationKey, 52))
userAddress := mload(add(reputationKey,72)) // 72, not 84, for the same reason as above. Is this being too clever? I don't think there are
// any unintended side effects here, but I'm not quite confortable enough with EVM's stack to be sure.
// Not sure what the alternative would be anyway.
}
bool decayCalculation = false;
if (decayCalculation) {
} else {
require(reputationUpdateLog[updateNumber].user == userAddress);
require(reputationUpdateLog[updateNumber].colony == colonyAddress);
require(reputationUpdateLog[updateNumber].skillId == skillId);
}
}
function proveBeforeReputationValue(uint256[9] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes agreeStateReputationValue, bytes32[] agreeStateSiblings) internal {
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; // We binary searched to the first disagreement, so the last agreement is the one before.
uint256 reputationValue;
assembly {
reputationValue := mload(add(agreeStateReputationValue, 32))
}
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, agreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline solidity
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
if (reputationValue == 0 && impliedRoot != jrh) {
// This implies they are claiming that this is a new hash.
return;
}
require(impliedRoot == jrh);
// They've actually verified whatever they claimed. We increment their challengeStepCompleted by one to indicate this.
// In the event that our opponent lied about this reputation not existing yet in the tree, they will both complete
// a call to respondToChallenge, but we will have a higher challengeStepCompleted value, and so they will be the ones
// eliminated.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
// I think this trick can be used exactly once, and only because this is the last function to be called in the challege,
// and I'm choosing to use it here. I *think* this is okay, because the only situation
// where we don't prove anything with merkle proofs in this whole dance is here.
}
function proveAfterReputationValue(uint256[9] u, bytes _reputationKey, bytes32[] reputationSiblings, bytes disagreeStateReputationValue, bytes32[] disagreeStateSiblings) internal {
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound;
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, disagreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes memory jhLeafValue = new bytes(64);
bytes memory firstDisagreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,5))) // 5 = U_DISAGREE_STATE_NNODES. Constants not supported by inline solidity.
mstore(add(jhLeafValue, 0x40), x)
mstore(add(firstDisagreeIdxBytes, 0x20), firstDisagreeIdx)
}
bytes32 impliedRoot = getImpliedRoot(firstDisagreeIdxBytes, jhLeafValue, u[U_DISAGREE_STATE_BRANCH_MASK], disagreeStateSiblings);
require(jrh==impliedRoot, "colony-invalid-after-reputation-proof");
}
function performReputationCalculation(uint256[9] u, bytes agreeStateReputationValueBytes, bytes disagreeStateReputationValueBytes, bytes previousNewReputationValueBytes) internal {
// TODO: Possibility of decay calculation
uint reputationTransitionIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
int256 amount;
uint256 agreeStateReputationValue;
uint256 disagreeStateReputationValue;
uint256 agreeStateReputationUID;
uint256 disagreeStateReputationUID;
assembly {
agreeStateReputationValue := mload(add(agreeStateReputationValueBytes, 32))
disagreeStateReputationValue := mload(add(disagreeStateReputationValueBytes, 32))
agreeStateReputationUID := mload(add(agreeStateReputationValueBytes, 64))
disagreeStateReputationUID := mload(add(disagreeStateReputationValueBytes, 64))
}
if (agreeStateReputationUID != 0) {
// i.e. if this was an existing reputation, then require that the ID hasn't changed.
// TODO: Situation where it is not an existing reputation
require(agreeStateReputationUID==disagreeStateReputationUID);
} else {
uint256 previousNewReputationUID;
assembly {
previousNewReputationUID := mload(add(previousNewReputationValueBytes, 64))
}
require(previousNewReputationUID+1 == disagreeStateReputationUID);
// Flag that we need to check that the reputation they supplied is in the 'agree' state.
// This feels like it might be being a bit clever, using this array to pass a 'return' value out of
// this function, without adding a new variable to the stack in the parent function...
u[U_REQUIRE_REPUTATION_CHECK] = 1;
}
// We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'.
// i.e. a reputation can't be negative.
if (reputationUpdateLog[reputationTransitionIdx].amount < 0 && uint(reputationUpdateLog[reputationTransitionIdx].amount * -1) > agreeStateReputationValue ) {
require(disagreeStateReputationValue == 0);
} else if (uint(reputationUpdateLog[reputationTransitionIdx].amount) + agreeStateReputationValue < agreeStateReputationValue) {
// We also don't allow reputation to overflow
require(disagreeStateReputationValue == 2**256 - 1);
} else {
// TODO: Is this safe? I think so, because even if there's over/underflows, they should
// still be the same number.
require(int(agreeStateReputationValue)+reputationUpdateLog[reputationTransitionIdx].amount == int(disagreeStateReputationValue));
}
}
function checkPreviousReputationInState(
uint256[9] u,
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings)
internal
{
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1; // We binary searched to the first disagreement, so the last agreement is the one before
bytes32 reputationRootHash = getImpliedRoot(previousNewReputationKey, previousNewReputationValue, u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK], previousNewReputationSiblings);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline assembly
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == disputeRounds[u[U_ROUND]][u[U_IDX]].jrh);
}
function saveProvedReputation(uint256[9] u, bytes previousNewReputationValue) internal {
uint256 previousReputationUID;
assembly {
previousReputationUID := mload(add(previousNewReputationValue,0x40))
}
// Save the index for tiebreak scenarios later.
disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = previousReputationUID;
}
function checkJRHProof1(bytes32 jrh, uint branchMask1, bytes32[] siblings1) internal {
// Proof 1 needs to prove that they started with the current reputation root hash
bytes32 reputationRootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash();
uint256 reputationRootHashNNodes = IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
bytes memory jhLeafValue = new bytes(64);
bytes memory zero = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
mstore(add(jhLeafValue, 0x40), reputationRootHashNNodes)
}
bytes32 impliedRoot = getImpliedRoot(zero, jhLeafValue, branchMask1, siblings1);
require(jrh==impliedRoot, "colony-invalid-jrh-proof-1");
}
function checkJRHProof2(uint round, uint index, bytes32 jrh, uint branchMask2, bytes32[] siblings2) internal {
// Proof 2 needs to prove that they finished with the reputation root hash they submitted, and the
// key is the number of updates in the reputation update log (implemented)
// plus the number of nodes in the last accepted update, each of which will have decayed once (not implemented)
// TODO: Account for decay calculations
uint256 nUpdates = reputationUpdateLog.length;
bytes memory nUpdatesBytes = new bytes(32);
disputeRounds[round][index].jrhNnodes = nUpdates + 1;
bytes32 submittedHash = disputeRounds[round][index].proposedNewRootHash;
uint256 submittedHashNNodes = disputeRounds[round][index].nNodes;
bytes memory jhLeafValue = new bytes(64);
assembly {
mstore(add(jhLeafValue, 0x20), submittedHash)
mstore(add(jhLeafValue, 0x40), submittedHashNNodes)
mstore(add(nUpdatesBytes, 0x20), nUpdates)
}
bytes32 impliedRoot = getImpliedRoot(nUpdatesBytes, jhLeafValue, branchMask2, siblings2);
require(jrh==impliedRoot, "colony-invalid-jrh-proof-2");
}
function startMemberOfPair(uint256 roundNumber, uint256 index) internal {
disputeRounds[roundNumber][index].lastResponseTimestamp = now;
disputeRounds[roundNumber][index].upperBound = disputeRounds[roundNumber][index].jrhNnodes;
disputeRounds[roundNumber][index].lowerBound = 0;
disputeRounds[roundNumber][index].provedPreviousReputationUID = 0;
if (disputeRounds[roundNumber][index].jrh != 0x0) {
// If this submission has a JRH, we give ourselves credit for it in the next round - it's possible
// that a submission got a bye without submitting a JRH, which will not have this starting '1'.
disputeRounds[roundNumber][index].challengeStepCompleted = 1;
} else {
disputeRounds[roundNumber][index].challengeStepCompleted = 0;
}
}
function startPairingInRound(uint256 roundNumber) internal {
uint256 nInRound = disputeRounds[roundNumber].length;
startMemberOfPair(roundNumber, nInRound-1);
startMemberOfPair(roundNumber, nInRound-2);
}
}
| TODO: Check this challenge is active. This require is necessary, but not a sufficient check (need to check we have an opponent, at least). | function respondToBinarySearchForChallenge(uint256 round, uint256 idx, bytes jhIntermediateValue, uint branchMask, bytes32[] siblings) public {
require(disputeRounds[round][idx].lowerBound!=disputeRounds[round][idx].upperBound);
uint256 targetNode = add(disputeRounds[round][idx].lowerBound, sub(disputeRounds[round][idx].upperBound, disputeRounds[round][idx].lowerBound) / 2);
bytes32 jrh = disputeRounds[round][idx].jrh;
bytes memory targetNodeBytes = new bytes(32);
}
assembly {
mstore(add(targetNodeBytes, 0x20), targetNode)
}
bytes32 impliedRoot = getImpliedRoot(targetNodeBytes, jhIntermediateValue, branchMask, siblings);
require(impliedRoot==jrh, "colony-invalid-binary-search-response");
processBinaryChallengeSearchResponse(round, idx, jhIntermediateValue, targetNode);
}
| 12,759,870 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/**
* @title Example
* @notice Example.sol is supposed to showcase how one can use `abi.encodeWithSignature()` to generate a hash that
* can be passed into `<address>.call{value}(calldata)` as seen in `calls()`
* @dev Store & retrieve value in a variable
*/
contract Example {
uint256 number;
/**
* @dev Return value
* @return value of 'number'
*/
function retrieve() public view returns (uint256) {
return number;
}
/**
* @dev Store value in variable
* @param num value to store
*/
function store(uint256 num) public {
number = num;
}
// generate signature (signed tx) in passable format to use with call()
// @parameter fnDetails to be store(uint256) --> NOTE: although this is not working, the tx carries through, but the state var: num, does not change.
function hash(string memory fnDetails, uint256 num) public view returns (bytes memory signedHash) {
bytes memory hexString = abi.encodeWithSignature(fnDetails, num);
return hexString;
}
// execute signed tx signature using global function .call()
function calls(bytes memory signature) public payable {
msg.sender.call{ value: msg.value }(signature);
}
}
| execute signed tx signature using global function .call() | function calls(bytes memory signature) public payable {
}
| 14,043,941 |
./full_match/4/0x766De7f2EdA6c3774cbe07149583d850A821DE77/sources/contracts/kapeikas2021.sol | limit the minimum amount for one transaction (ETH) check if the milestone requires user to be whitelisted limit the number of tokens that user can buy according to the hardcap of the current milestone (10SET) | function internalFallback() internal returns (uint) {
require(!isPause, "Contract paused");
uint256 milestoneIndex = currentMilestone();
Milestone storage milestone = milestones[milestoneIndex];
uint256 limitedInvestValue = msg.value;
require(limitedInvestValue >= milestone.minInvestedLimit, "The amount is too small");
if (whitelistedMilestones[milestoneIndex]) {
require(whitelist[_msgSender()], "The address must be whitelisted!");
}
if (limitedInvestValue > maxAllowableValue) {
limitedInvestValue = maxAllowableValue;
}
require(limitedInvestValue > 0, "Investment limit exceeded!");
uint256 tokensWithBonus = tokensWithoutBonus;
if (milestone.bonus > 0) {
tokensWithBonus = tokensWithoutBonus.add(tokensWithoutBonus.mul(milestone.bonus).div(percentRate));
}
if (milestone.tokensSold.add(tokensWithBonus) > milestone.hardcapInTokens) {
tokensWithBonus = milestone.hardcapInTokens.sub(milestone.tokensSold);
if (milestone.bonus > 0) {
tokensWithoutBonus = tokensWithBonus.mul(percentRate).div(percentRate + milestone.bonus);
}
}
uint256 change = msg.value - tokenBasedLimitedInvestValue;
milestone.tokensSold = milestone.tokensSold.add(tokensWithBonus);
balances[milestoneIndex][_msgSender()] = balances[milestoneIndex][_msgSender()].add(tokenBasedLimitedInvestValue);
wallet.transfer(tokenBasedLimitedInvestValue);
if (change > 0) {
_msgSender().transfer(change);
}
return tokensWithBonus;
}
| 741,674 |
pragma solidity 0.5.16;
import "./CosmosWhiteListStorage.sol";
/**
* @title WhiteList
* @dev WhiteList contract records the ERC 20 list that can be locked in BridgeBank.
**/
contract CosmosWhiteList is CosmosWhiteListStorage {
bool private _initialized;
/*
* @dev: Event declarations
*/
event LogWhiteListUpdate(address _token, bool _value);
function initialize() public {
require(!_initialized, "Initialized");
_cosmosTokenWhiteList[address(0)] = true;
_initialized = true;
}
/*
* @dev: Modifier to restrict erc20 can be locked
*/
modifier onlyCosmosTokenWhiteList(address _token) {
require(
getCosmosTokenInWhiteList(_token),
"Only token in whitelist can be transferred to cosmos"
);
_;
}
/*
* @dev: Set the token address in whitelist
*
* @param _token: ERC 20's address
* @param _inList: set the _token in list or not
* @return: new value of if _token in whitelist
*/
function setTokenInCosmosWhiteList(address _token, bool _inList)
internal
returns (bool)
{
_cosmosTokenWhiteList[_token] = _inList;
emit LogWhiteListUpdate(_token, _inList);
return _inList;
}
/*
* @dev: Get if the token in whitelist
*
* @param _token: ERC 20's address
* @return: if _token in whitelist
*/
function getCosmosTokenInWhiteList(address _token) public view returns (bool) {
return _cosmosTokenWhiteList[_token];
}
} | : Get if the token in whitelist _token: ERC 20's address return: if _token in whitelist/ | function getCosmosTokenInWhiteList(address _token) public view returns (bool) {
return _cosmosTokenWhiteList[_token];
}
| 15,828,860 |
pragma solidity ^0.5.0;
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol';
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Pausable.sol';
import 'openzeppelin-solidity/contracts/drafts/Counter.sol';
import './StableToken.sol';
import './ShopRole.sol';
contract GiftCertificate is Ownable, ERC721Full, ERC721Pausable, ShopRole {
using Counter for Counter.Counter;
using SafeMath for uint256;
Counter.Counter private tokenId;
uint256 _rate;
uint256 _reserved;
address _stabletoken_addr;
mapping (uint256 => uint256 ) _values;
event Fund(
address from,
uint256 amount
);
event Issue(
address to,
uint256 amount,
uint256 ID
);
event Redeem(
uint256 ID,
address to,
uint256 amount
);
event Refund(
address to,
uint256 amount
);
constructor( string memory name, string memory symbol, uint256 rate, address stabletoken_addr) ERC721Full(name, symbol) public {
require(rate % 10 == 0, 'The bonus percentage must be multiples of 10.');
_rate = rate;
_stabletoken_addr = stabletoken_addr;
}
/*
*@dev function to fund the contract for promotion/discount.
* requires the ERC20 to be approved for this contract at least for the amount requested
* @param amount the user supplied amount of ERC20 tokens, we only accept multiples of 50.
*/
function fund(uint256 amount) public onlyOwner whenNotPaused {
StableToken st = StableToken(_stabletoken_addr);
require(amount <= st.allowance(msg.sender, address(this)), "You did not approve this amount.");
st.transferFrom(msg.sender, address(this), amount);
emit Fund(msg.sender, amount);
}
/*
*@dev function to issue a gift certificate.
* requires the ERC20 to be approved for this contract at least for the amount requested
* @param amount the user supplied amount of ERC20 tokens, we only accept multiples of 50.
*/
function issue(uint256 amount) public whenNotPaused returns (uint256){
require(amount != 0, 'Please be reasonable.');
require(amount % 10 == 0, 'You must buy in multiples of 10.');
StableToken st = StableToken(_stabletoken_addr);
uint256 ID = tokenId.next();
uint256 balance = st.balanceOf(address(this));
uint256 available = balance.sub(_reserved);
//as both amount and _rate are multiples of 10 this should always result in an int.
uint256 bonus = amount.mul(_rate).div(100);
require(bonus <= available, "We cannot issue a gift certificate for this value as it would exceed our budget.");
require(amount <= st.allowance(msg.sender, address(this)), "You did not approve this amount.");
_values[ID] = amount.add(bonus);
_reserved = _reserved.add(_values[ID]);
super._mint(msg.sender, ID);
st.transferFrom(msg.sender, address(this), amount);
emit Issue(msg.sender, amount, ID);
return ID;
}
/*
*@dev function to allow a shop to redeem a gift certificate.
*@param ID the ID of the GFT token to redeem
* an approved shop can redeem the certificate for the total amount of ERC20 tokens
*/
function redeem(uint256 ID) public whenNotPaused onlyShop {
_redeem(ID);
}
/*
*@dev function to allow a customer to redeem a gift certificate when the contract has been paused.
*@param ID the ID of the GFT token to redeem
* anyone can redeem their certificate for the total amount of ERC20 tokens
*/
function redeemPaused(uint256 ID) public whenPaused {
_redeem(ID);
}
/*
*@dev internal function to redeem a gift certificate.
*@param ID the ID of the GFT token to redeem
*/
function _redeem(uint256 ID) internal {
require(super._exists(ID), "Gift certificate does not exist.");
require(super._isApprovedOrOwner(msg.sender, ID), "Not authorized to redeem this gift certificate.");
uint256 value = _values[ID];
_reserved = _reserved.sub(value);
super._burn(msg.sender, ID);
StableToken st = StableToken(_stabletoken_addr);
st.transfer(msg.sender, value);
emit Redeem( ID, msg.sender, value);
}
/*
*@dev function to allow the owner to return all the unused STBL tokens when the contract is Paused and all GFT tokens have been redeemed
*/
function refund() public whenPaused onlyOwner{
require(_reserved == 0, 'A part of the STBL tokens are still reserved.');
uint256 total_supply = super.totalSupply();
require(total_supply == 0, 'There are still GFT tokens that are not redeemed.');
StableToken st = StableToken(_stabletoken_addr);
uint256 stbl_balance = st.balanceOf(address(this));
st.transfer(msg.sender, stbl_balance);
emit Refund(msg.sender, stbl_balance);
}
}
| function to allow a customer to redeem a gift certificate when the contract has been paused. ID the ID of the GFT token to redeem anyone can redeem their certificate for the total amount of ERC20 tokens/ | function redeemPaused(uint256 ID) public whenPaused {
_redeem(ID);
}
| 6,465,330 |
/**
*Submitted for verification at Etherscan.io on 2021-05-24
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
function initialize() external;
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function symbol() external view returns (string memory);
function decimals() external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function mint(address account, uint amount) external;
function burn(address account, uint amount) external;
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MasterPool is Ownable {
struct UserInfo {
uint amount;
uint rewardDebt;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint allocPoints; // How many allocation points assigned to this pool. RewardTokens to distribute per block.
uint lastRewardBlock; // Last block number that RewardTokens distribution occurs.
uint accRewardTokenPerShare; // Accumulated RewardTokens per share, times 1e12. See below.
}
struct PoolPosition {
uint pid;
bool added; // To prevent duplicates.
}
IERC20 public rewardToken;
uint public rewardTokenPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint => mapping (address => UserInfo)) public userInfo;
mapping (address => PoolPosition) public pidByToken;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint public totalAllocPoints;
// The block number when RewardToken mining starts.
uint public startBlock;
event Deposit(address indexed user, uint indexed pid, uint amount);
event Withdraw(address indexed user, uint indexed pid, uint amount);
event EmergencyWithdraw(address indexed user, uint indexed pid, uint amount);
event PoolUpdate(
address indexed lpToken,
uint indexed pid,
uint allocPoints,
bool indexed withUpdate
);
constructor(
IERC20 _rewardToken,
uint _rewardTokenPerBlock,
uint _startBlock
) {
rewardToken = _rewardToken;
rewardTokenPerBlock = _rewardTokenPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(address _lpToken, uint _allocPoints, bool _withUpdate) public onlyOwner {
require(pidByToken[_lpToken].added == false, "MasterPool: already added");
if (_withUpdate) {
massUpdatePools();
}
uint lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoints = totalAllocPoints + _allocPoints;
poolInfo.push(PoolInfo({
lpToken: IERC20(_lpToken),
allocPoints: _allocPoints,
lastRewardBlock: lastRewardBlock,
accRewardTokenPerShare: 0
}));
pidByToken[_lpToken] = PoolPosition({
pid: poolInfo.length - 1,
added: true
});
emit PoolUpdate(_lpToken, poolInfo.length - 1, _allocPoints, _withUpdate);
}
// Update the given pool's RewardToken allocation point. Can only be called by the owner.
function set(uint _pid, uint _allocPoints, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoints = totalAllocPoints - poolInfo[_pid].allocPoints + _allocPoints;
poolInfo[_pid].allocPoints = _allocPoints;
emit PoolUpdate(address(poolInfo[_pid].lpToken), _pid, _allocPoints, _withUpdate);
}
// View function to see pending RewardTokens on frontend.
function pendingRewards(uint _pid, address _user) external view returns (uint) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint accRewardTokenPerShare = pool.accRewardTokenPerShare;
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint multiplier = block.number - pool.lastRewardBlock;
uint rewardTokenReward = multiplier * rewardTokenPerBlock * pool.allocPoints / totalAllocPoints;
accRewardTokenPerShare += rewardTokenReward * 1e12 / lpSupply;
}
return (user.amount * accRewardTokenPerShare / 1e12) - user.rewardDebt;
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint length = poolInfo.length;
for (uint pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint multiplier = block.number - pool.lastRewardBlock;
uint rewardTokenReward = multiplier * rewardTokenPerBlock * pool.allocPoints / totalAllocPoints;
pool.accRewardTokenPerShare += rewardTokenReward * 1e12 / lpSupply;
pool.lastRewardBlock = block.number;
}
function deposit(uint _pid, uint _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint pending = (user.amount * pool.accRewardTokenPerShare / 1e12) - user.rewardDebt;
safeRewardTokenTransfer(msg.sender, pending);
}
pool.lpToken.transferFrom(address(msg.sender), address(this), _amount);
user.amount += _amount;
user.rewardDebt = user.amount * pool.accRewardTokenPerShare / 1e12;
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint _pid, uint _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "MasterPool: user.amount >= _amount");
updatePool(_pid);
uint pending = (user.amount * pool.accRewardTokenPerShare / 1e12) - user.rewardDebt;
safeRewardTokenTransfer(msg.sender, pending);
user.amount = user.amount - _amount;
user.rewardDebt = user.amount * pool.accRewardTokenPerShare / 1e12;
pool.lpToken.transfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.transfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Allows to migrate rewards to a new staking contract.
function migrateRewards(address _recipient, uint _amount) public onlyOwner {
rewardToken.transfer(_recipient, _amount);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough RewardTokens.
function safeRewardTokenTransfer(address _to, uint _amount) internal {
uint rewardTokenBal = rewardToken.balanceOf(address(this));
if (_amount > rewardTokenBal) {
rewardToken.transfer(_to, rewardTokenBal);
} else {
rewardToken.transfer(_to, _amount);
}
}
} | Update reward variables of the given pool to be up-to-date. | function updatePool(uint _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint multiplier = block.number - pool.lastRewardBlock;
uint rewardTokenReward = multiplier * rewardTokenPerBlock * pool.allocPoints / totalAllocPoints;
pool.accRewardTokenPerShare += rewardTokenReward * 1e12 / lpSupply;
pool.lastRewardBlock = block.number;
}
| 7,735,987 |
pragma solidity ^0.4.23;
/**
* Math operations with safety checks
*/
library SafeMath {
/**
* @dev Multiplies two numbers, revert()s on overflow.
*/
function mul(uint256 a, uint256 b) internal 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 returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
/**
* @dev Subtracts two numbers, revert()s on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, revert()s on overflow.
*/
function add(uint256 a, uint256 b) internal returns (uint256 c) {
c = a + b;
assert(c >= a && c >= b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, 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.add(4)) {
revert();
}
_;
}
/**
* @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) {
require(_to != 0x0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit 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 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 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) {
require(_to != 0x0);
uint _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert() if this condition is not met
// if (_value > _allowance) revert();
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit 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)) revert();
allowed[msg.sender][_spender] = _value;
emit 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 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 revert()s if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
/**
* @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 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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
if (paused) revert();
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
if (!paused) revert();
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* Pausable token
*
* Simple ERC20 Token example, with pausable token creation
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) whenNotPaused {
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a time has passed
*/
contract TokenTimelock {
// ERC20 basic token contract being held
ERC20Basic token;
// beneficiary of tokens after they are released
address beneficiary;
// timestamp where token release is enabled
uint releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint _releaseTime) {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @dev beneficiary claims tokens held by time lock
*/
function claim() {
require(msg.sender == beneficiary);
require(now >= releaseTime);
uint amount = token.balanceOf(this);
require(amount > 0);
token.transfer(beneficiary, amount);
}
}
/**
* @title hun mun chain Token
* @dev hun mun chain Token contract
*/
contract HMCToken is PausableToken {
using SafeMath for uint256;
function () {
//if ether is sent to this address, send it back.
revert();
}
string public name = "hun mun chain";
string public symbol = "HMC";
uint8 public decimals = 18;
uint public totalSupply = 1000000000000000000000000000;
event TimeLock(address indexed to, uint value, uint time);
event Burn(address indexed burner, uint256 value);
function HMCToken() {
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/**
* @dev transfer timelocked tokens
*/
function transferTimelocked(address _to, uint256 _amount, uint256 _releaseTime)
onlyOwner whenNotPaused returns (TokenTimelock) {
require(_to != 0x0);
TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime);
transfer(timelock,_amount);
emit TimeLock(_to, _amount,_releaseTime);
return timelock;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) onlyOwner whenNotPaused {
_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);
}
} | Multiplies two numbers, revert()s on overflow./ | function mul(uint256 a, uint256 b) internal returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
| 634,700 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./CelebrityContract.sol";
import "./AutographContract.sol";
contract AutographRequestContract is Ownable {
// Structs
struct Request {
address from;
address to;
uint price;
uint responseTime;
uint created;
}
// Variables
CelebrityContract private celebrityContract;
AutographContract private autographContract;
Request[] private requests;
uint numberOfPendingRequests;
uint private feePercent;
// Events
event RequestCreated(uint id, address indexed from, address indexed to, uint price, uint responseTime, uint created);
event RequestDeleted(uint id, address indexed from, address indexed to, uint price, uint responseTime, uint created);
event RequestSigned(uint id, address indexed from, address indexed to, uint price, uint responseTime, uint created, string nftHash, string metadata);
event FeePercentChanged(uint feePercent);
/**
* Contract constructor.
* - _celebrityContract: Celebrity contract address.
* - _autographContract: NFT Token address.
*/
constructor(address _celebrityContract, address _autographContract) {
celebrityContract = CelebrityContract(_celebrityContract);
autographContract = AutographContract(_autographContract);
feePercent = 10; // %
}
/**
* Function used to request a new NFT (autograph) to a celeb.
* - to: Celeb address or recipient.
* - responseTime: Request response time.
*/
function createRequest(address to) public payable {
(,,uint price, uint responseTime) = celebrityContract.getCelebrity(to);
require(msg.value == price, 'The amount paid is not equal to the sale price');
// Adding paid price to contract balance
Request memory newRequest = Request(msg.sender, to, price, responseTime, block.timestamp);
requests.push(newRequest);
uint id = requests.length - 1;
numberOfPendingRequests += 1;
emit RequestCreated(id, newRequest.from, newRequest.to, newRequest.price, newRequest.responseTime, newRequest.created);
}
/**
* Method used to remove a request after the locking period expired.
* - id: Request index.
* - responseTime: Request response time.
*/
function deleteRequest(uint id) public {
Request memory request = requests[id];
require(request.from == msg.sender, 'You are not the owner of the request');
require(block.timestamp >= request.created + (request.responseTime * 1 days), 'You must wait the response time to delete this request');
// Transfering amount payed to user
payable(msg.sender).transfer(request.price);
delete requests[id];
numberOfPendingRequests -= 1;
emit RequestDeleted(id, request.from, request.to, request.price, request.responseTime, request.created);
}
/**
* Method used to sign a pending request.
* - id: Request index.
* - nftHash: NFT hash parameter.
* - metadata: Autograph metadata.
*/
function signRequest(uint id, string memory nftHash, string memory metadata) public {
Request memory request = requests[id];
require(request.to == msg.sender, 'You are not the recipient of the request');
require(address(this).balance >= request.price, 'Balance should be greater than request price');
// Minting the NFT
uint tokenId = autographContract.mint(request.from, nftHash, metadata);
require(autographContract.ownerOf(tokenId) == request.from, 'Token was not created correctly');
// Adding request price to celeb balance
address payable addr = payable(request.to);
address payable ownerAddr = payable(owner());
// Calculating and transfering fees
uint fee = request.price * feePercent / 100;
ownerAddr.transfer(fee);
// Transfering payment to celebrity
addr.transfer(request.price - fee);
// Deleting request
delete requests[id];
numberOfPendingRequests -= 1;
emit RequestSigned(id, request.from, request.to, request.price, request.responseTime, request.created, nftHash, metadata);
}
/**
* Method used to return the contract balance.
*/
function getBalance() public view returns (uint) {
return address(this).balance;
}
/**
* Gets request information by id.
* - id: Request identifier.
*/
function getRequest(uint id) public view returns (
address from, address to, uint price, uint responseTime, uint created) {
return (
requests[id].from,
requests[id].to,
requests[id].price,
requests[id].responseTime,
requests[id].created
);
}
/**
* Gets total number of requests.
*/
function getTotalSupply() public view returns (uint) {
return requests.length;
}
/**
* Gets number of pending requests.
*/
function getNumberOfPendingRequests() public view returns (uint) {
return numberOfPendingRequests;
}
/**
* Sets fees percent.
*/
function setFeePercent(uint _feePercent) public onlyOwner {
feePercent = _feePercent;
emit FeePercentChanged(feePercent);
}
/**
* Returns contract fee percent.
*/
function getFeePercent() public view onlyOwner returns (uint) {
return feePercent;
}
} | Gets request information by id. - id: Request identifier./ | function getRequest(uint id) public view returns (
address from, address to, uint price, uint responseTime, uint created) {
return (
requests[id].from,
requests[id].to,
requests[id].price,
requests[id].responseTime,
requests[id].created
);
}
| 5,363,902 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
import {UZV1BasePool} from "./UZV1BasePool.sol";
/**
* @title UnizenBasicRewardPool
* @author Unizen
* @notice Reward pool for ERC20 tokens
**/
contract UZV1BasicRewardPool is UZV1BasePool {
using SafeMath for uint256;
/* === STATE VARIABLES === */
function initialize(address _router, address _accessToken)
public
override
initializer
{
UZV1BasePool.initialize(_router, _accessToken);
}
/* === VIEW FUNCTIONS === */
function canReceiveRewards() external pure override returns (bool) {
return true;
}
function getPoolType() external pure override returns (uint8) {
return 0;
}
function isPayable() public pure override returns (bool) {
return false;
}
function isNative() public pure override returns (bool) {
return false;
}
/* === MUTATING FUNCTIONS === */
/// user functions
function _safeClaim(address _user, uint256 _amount)
internal
override
returns (uint256)
{
IERC20 _token = IERC20(_poolData.token);
uint256 _balance = _token.balanceOf(address(this));
uint256 _realAmount = (_amount <= _balance) ? _amount : _balance;
if (_realAmount == 0) return 0;
_poolStakerUser[_user].totalSavedRewards = _poolStakerUser[_user]
.totalSavedRewards
.add(_realAmount);
_totalRewardsLeft = _totalRewardsLeft.sub(_realAmount);
SafeERC20.safeTransfer(_token, _user, _realAmount);
emit RewardClaimed(_user, _realAmount);
return _realAmount;
}
}
// 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library SharedDataTypes {
// struct for returning snapshot values
struct StakeSnapshot {
// initial block number snapshoted
uint256 startBlock;
// end block number snapshoted
uint256 endBlock;
// staked amount at initial block
uint256 stakedAmount;
// total value locked at end block
uint256 tokenTVL;
}
// general staker user information
struct StakerUser {
// snapshotted stakes of the user per token (token => block.number => stakedAmount)
mapping(address => mapping(uint256 => uint256)) stakedAmountSnapshots;
// snapshotted stakes of the user per token keys (token => block.number[])
mapping(address => uint256[]) stakedAmountKeys;
// current stakes of the user per token
mapping(address => uint256) stakedAmount;
// total amount of holder tokens
uint256 zcxhtStakedAmount;
}
// information for stakeable tokens
struct StakeableToken {
// snapshotted total value locked (TVL) (block.number => totalValueLocked)
mapping(uint256 => uint256) totalValueLockedSnapshots;
// snapshotted total value locked (TVL) keys (block.number[])
uint256[] totalValueLockedKeys;
// current total value locked (TVL)
uint256 totalValueLocked;
uint256 weight;
bool active;
}
// POOL DATA
// data object for a user stake on a pool
struct PoolStakerUser {
// saved / withdrawn rewards of user
uint256 totalSavedRewards;
// total purchased allocation
uint256 totalPurchasedAllocation;
// native address, if necessary
string nativeAddress;
// date/time when user has claimed the reward
uint256 claimedTime;
}
// flat data type of stake for UI
struct FlatPoolStakerUser {
address[] tokens;
uint256[] amounts;
uint256 pendingRewards;
uint256 totalPurchasedAllocation;
uint256 totalSavedRewards;
uint256 claimedTime;
PoolState state;
UserPoolState userState;
}
// UI information for pool
// data will be fetched via github token repository
// blockchain / cAddress being the most relevant values
// for fetching the correct token data
struct PoolInfo {
// token name
string name;
// name of blockchain, as written on github
string blockchain;
// tokens contract address on chain
string cAddress;
}
// possible states of the reward pool
enum PoolState {
pendingStaking,
staking,
pendingPayment,
payment,
pendingDistribution,
distribution,
retired
}
// possible states of the reward pool's user
enum UserPoolState {
notclaimed,
claimed,
rejected,
missed
}
// input data for new reward pools
struct PoolInputData {
// total rewards to distribute
uint256 totalRewards;
// start block for distribution
uint256 startBlock;
// end block for distribution
uint256 endBlock;
// erc token address
address token;
// pool type
uint8 poolType;
// information about the reward token
PoolInfo tokenInfo;
}
struct PoolData {
PoolState state;
// pool information for the ui
PoolInfo info;
// start block of staking rewards
uint256 startBlock;
// end block of staking rewards
uint256 endBlock;
// start block of payment period
uint256 paymentStartBlock;
// end block of payment period
uint256 paymentEndBlock;
// start block of distribution period
uint256 distributionStartBlock;
// end block of distribution period
uint256 distributionEndBlock;
// total rewards for allocation
uint256 totalRewards;
// rewards per block
uint256 rewardsPerBlock;
// price of a single payment token
uint256 rewardTokenPrice;
// type of the pool
uint8 poolType;
// address of payment token
address paymentToken;
// address of reward token
address token;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IUZV1RewardPool} from "../interfaces/pools/IUZV1RewardPool.sol";
import {IUZV1Router} from "../interfaces/IUZV1Router.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
import {UZV1ProAccess} from "../membership/UZV1ProAccess.sol";
/**
* @title UnizenBasePool
* @author Unizen
* @notice Base Reward pool for Unizen. Serves as base for all existing pool types,
* to ease more pool types and reduce duplicated code.
* The base rewards calculation approach is based on the great work of MasterChef.sol by SushiSwap.
* https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol
**/
abstract contract UZV1BasePool is IUZV1RewardPool, UZV1ProAccess {
using SafeMath for uint256;
/* === STATE VARIABLES === */
// router address
IUZV1Router internal _router;
address public override factory;
// data of user stakes and rewards
mapping(address => SharedDataTypes.PoolStakerUser) internal _poolStakerUser;
// pool data
SharedDataTypes.PoolData internal _poolData;
// total rewards left
uint256 internal _totalRewardsLeft;
modifier onlyFactoryOrOwner() {
require(
_msgSender() == factory || _msgSender() == owner(),
"ONLY_FACTORY_OR_OWNER"
);
_;
}
function initialize(address _newRouter, address _accessToken)
public
virtual
override
initializer
{
UZV1ProAccess.initialize(_accessToken);
_router = IUZV1Router(_newRouter);
emit PoolInitiated();
}
function setFactory(address _factory) external override onlyOwner {
factory = _factory;
}
function transferOwnership(address _newOwner)
public
override(IUZV1RewardPool, OwnableUpgradeable)
onlyOwner
{
OwnableUpgradeable.transferOwnership(_newOwner);
}
/* === VIEW FUNCTIONS === */
function getUserPoolStake(address _user)
public
view
virtual
override
returns (SharedDataTypes.PoolStakerUser memory)
{
return _poolStakerUser[_user];
}
function getPendingRewards(address _user)
external
view
virtual
override
returns (uint256 reward)
{
return _getPendingRewards(_user);
}
/**
* @dev Calculates the current pending reward amounts of a user
* @param _user The user to check
*
* @return reward uint256 pending amount of user rewards
**/
function _getPendingRewards(address _user)
internal
view
returns (uint256 reward)
{
uint256 _totalRewards = _getTotalRewards(_user);
return
_totalRewards > _poolStakerUser[_user].totalSavedRewards
? _totalRewards.sub(_poolStakerUser[_user].totalSavedRewards)
: 0;
}
/**
* @dev Calculates the current total reward amounts of a user
* @param _user The user to check
*
* @return reward uint256 total amount of user rewards
**/
function _getTotalRewards(address _user)
internal
view
returns (uint256 reward)
{
// no need to calculate, if rewards haven't started yet
if (block.number < _poolData.startBlock) return 0;
// get all tokens
(
address[] memory _allTokens,
,
uint256[] memory _weights,
uint256 _combinedWeight
) = _router.getAllTokens(_getLastRewardBlock());
// loop through all active tokens and get users currently pending reward
for (uint8 i = 0; i < _allTokens.length; i++) {
// read user stakes for every token
SharedDataTypes.StakeSnapshot[] memory _snapshots = _router
.getUserStakesSnapshots(
_user,
_allTokens[i],
_poolData.startBlock,
_getLastRewardBlock()
);
// calculates reward for every snapshoted block period
for (uint256 bl = 0; bl < _snapshots.length; bl++) {
// calculate pending rewards for token and add it to total pending reward amount
reward = reward.add(
_calculateTotalRewardForToken(
_snapshots[bl].stakedAmount,
_weights[i],
_combinedWeight,
_snapshots[bl].tokenTVL,
_snapshots[bl].endBlock.sub(_snapshots[bl].startBlock)
)
);
}
}
}
/**
* @dev Returns whether the pool is currently active
*
* @return bool active status of pool
**/
function isPoolActive() public view virtual override returns (bool) {
return (block.number >= _poolData.startBlock &&
block.number <= _poolData.endBlock);
}
/**
* @dev Returns whether the pool can be payed with a token
*
* @return bool status if pool is payable
**/
function isPayable() public view virtual override returns (bool);
/**
* @dev Returns whether the pool is a base or native pool
*
* @return bool True, if pool distributes native rewards
**/
function isNative() public view virtual override returns (bool);
/**
* @dev Returns all relevant information of an pool, excluding the stakes
* of users.
*
* @return PoolData object
**/
function getPoolInfo()
external
view
virtual
override
returns (SharedDataTypes.PoolData memory)
{
SharedDataTypes.PoolData memory _data = _poolData;
_data.state = getPoolState();
return _data;
}
/**
* @dev Returns the current state of the pool. Not all states
* are available on every pool type. f.e. payment
*
* @return PoolState State of the current phase
* * pendingStaking
* * staking
* * retired
**/
function getPoolState()
public
view
virtual
override
returns (SharedDataTypes.PoolState)
{
// if current block is bigger than end block, return retired state
if (block.number > _poolData.endBlock) {
return SharedDataTypes.PoolState.retired;
}
// if current block is within start and end block, return staking phase
if (
block.number >= _poolData.startBlock &&
block.number <= _poolData.endBlock
) {
return SharedDataTypes.PoolState.staking;
}
// otherwise, pool is in pendingStaking state
return SharedDataTypes.PoolState.pendingStaking;
}
/**
* @dev Returns the current state of the pool user
*
* @return UserPoolState State of the user for the current phase
* * notclaimed
* * claimed
* * rejected
* * missed
**/
function getUserPoolState()
public
view
virtual
override
returns (SharedDataTypes.UserPoolState)
{
return SharedDataTypes.UserPoolState.notclaimed;
}
/**
* @dev Returns the current type of the pool
*
* @return uint8 id of used pool type
**/
function getPoolType() external view virtual override returns (uint8);
/**
* @dev Returns all relevant staking data for a user.
*
* @param _user address of user to check
*
* @return FlatPoolStakerUser data object, containing all information about the staking data
* * total tokens staked
* * total saved rewards (saved/withdrawn)
* * array with stakes for each active token
**/
function getUserInfo(address _user)
public
view
virtual
override
returns (SharedDataTypes.FlatPoolStakerUser memory)
{
SharedDataTypes.FlatPoolStakerUser memory _userData;
// use data from staking contract
uint256[] memory _userStakes = _router.getUserStakes(
_user,
_getLastRewardBlock()
);
// get all tokens
(address[] memory _allTokens, , , ) = _router.getAllTokens();
_userData.totalSavedRewards = _poolStakerUser[_user].totalSavedRewards;
_userData.pendingRewards = _getPendingRewards(_user);
_userData.amounts = new uint256[](_allTokens.length);
_userData.tokens = new address[](_allTokens.length);
for (uint8 i = 0; i < _allTokens.length; i++) {
_userData.tokens[i] = _allTokens[i];
_userData.amounts[i] = _userStakes[i];
}
_userData.state = getPoolState();
_userData.userState = getUserPoolState();
return _userData;
}
/**
* @dev Returns whether the pool pays out any rewards. Usually true for onchain and
* false of off-chain reward pools.
*
* @return bool True if the user can receive rewards
**/
function canReceiveRewards() external view virtual override returns (bool);
/**
* @dev Returns the rewards that are left on the pool. This can be different, based
* on the type of pool. While basic reward pools will just return the reward token balance,
* off-chain pools will just store virtual allocations for users and incubators have different
* returns, based on their current pool state
*
* @return uint256 Amount of rewards left
**/
function getAmountOfOpenRewards()
external
view
virtual
override
returns (uint256)
{
return _totalRewardsLeft;
}
/**
* @dev Returns the start block for staking
* @return uint256 Staking start block number
**/
function getStartBlock() public view virtual override returns (uint256) {
return _poolData.startBlock;
}
/**
* @dev Returns the end block for staking
* @return uint256 Staking end block number
**/
function getEndBlock() public view virtual override returns (uint256) {
return _poolData.endBlock;
}
/**
* @dev Returns start and end blocks for
* all existing stages of the pool
* @return uint256[] Array with all block numbers. Each phase always has startBlock, endBlock
*/
function getTimeWindows()
external
view
virtual
override
returns (uint256[] memory)
{
uint256[] memory timeWindows = new uint256[](2);
timeWindows[0] = getStartBlock();
timeWindows[1] = getEndBlock();
return timeWindows;
}
/* === MUTATING FUNCTIONS === */
/// user functions
function pay(address _user, uint256 _amount)
external
virtual
override
onlyRouterOrProAccess(_msgSender())
returns (uint256 refund)
{
revert();
}
function claimRewards(address _user)
external
virtual
override
whenNotPaused
onlyRouterOrProAccess(_msgSender())
{
_claimRewards(_user);
}
function _claimRewards(address _user) internal virtual {
uint256 _pendingRewards = _getPendingRewards(_user);
// check if there are pending rewards
if (_pendingRewards > 0) {
// claim rewards
_safeClaim(_user, _pendingRewards);
}
}
/**
* @dev Allows the user to set a custom native address as receiver of rewards
* as these rewards will be distributed off-chain.
*
* @param _user address of the user, we want to update
* @param _receiver string users native address, where rewards will be sent to
**/
function setNativeAddress(address _user, string calldata _receiver)
external
override
onlyRouterOrProAccess(_msgSender())
{
require(isNative() == true, "NO_NATIVE_ADDR_REQ");
require(_user != address(0), "ZERO_ADDRESS");
require(bytes(_receiver).length > 0, "EMPTY_RECEIVER");
// if sender is not router, sender and user have to
// be identical
if (_msgSender() != address(_router)) {
require(_msgSender() == _user, "FORBIDDEN");
}
_poolStakerUser[_user].nativeAddress = _receiver;
}
/**
* @dev Returns the users current address as string, or the user provided
* native address, if the pool is a native reward pool
*
* @param user address of the user
* @return receiverAddress string of the users receiving address
*/
function getUserReceiverAddress(address user)
external
view
override
returns (string memory receiverAddress)
{
require(user != address(0), "ZERO_ADDRESS");
receiverAddress = (isNative() == true)
? _poolStakerUser[user].nativeAddress
: _addressToString(user);
}
// helpers to convert address to string
// https://ethereum.stackexchange.com/questions/72677/convert-address-to-string-after-solidity-0-5-x
function _addressToString(address _addr)
internal
pure
returns (string memory)
{
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(51);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < 20; i++) {
str[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
str[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(str);
}
/**
* @dev Calculates the last reward block
* @return uint256 Last reward block (block.number or _poolData.endBlock)
**/
function _getLastRewardBlock() internal view virtual returns (uint256) {
return
(block.number <= _poolData.endBlock)
? block.number
: _poolData.endBlock;
}
/**
* @dev Safety function that takes care of claiming amounts that
* exceed the reward that is left, in case there is a slight offset
* due to rounding issues.
*
* @param _user The user we want to send rewards to
* @param _amount The amount of rewards that should be claimed / sent
**/
function _safeClaim(address _user, uint256 _amount)
internal
virtual
returns (uint256)
{
uint256 _realAmount = (_amount <= _totalRewardsLeft)
? _amount
: _totalRewardsLeft;
require(_realAmount > 0, "ZERO_REWARD_AMOUNT");
_poolStakerUser[_user].totalSavedRewards = _poolStakerUser[_user]
.totalSavedRewards
.add(_realAmount);
_totalRewardsLeft = _totalRewardsLeft.sub(_realAmount);
emit RewardClaimed(_user, _realAmount);
return _realAmount;
}
function _rewardsForToken(
uint256 _weight,
uint256 _combinedWeight,
uint256 _tvl,
uint256 _blocks
) internal view returns (uint256) {
uint256 _reward = _blocks
.mul(_poolData.rewardsPerBlock)
.mul(_weight)
.div(_combinedWeight);
if (_tvl > 0) {
return _reward.mul(1e18).div(_tvl);
} else {
return 0;
}
}
function _calculateTotalRewardForToken(
uint256 _userStakes,
uint256 _weight,
uint256 _combinedWeight,
uint256 _tvl,
uint256 _blocks
) internal view returns (uint256 reward) {
uint256 _rewardsPerShare;
// we only need to calculate this, if the user holds any
// amount of this token
if (_userStakes > 0) {
// check if we need to calculate the rewards for more than the current block
if (_tvl > 0) {
// calculate the rewards per share
_rewardsPerShare = _rewardsForToken(
_weight,
_combinedWeight,
_tvl,
_blocks
);
// check if there is any reward to calculate
if (_rewardsPerShare > 0) {
// get the current reward for users stakes
reward = _userStakes.mul(_rewardsPerShare).div(1e18);
}
}
}
}
/// control functions
/**
* @dev Withdrawal function to remove payments, leftover rewards or tokens sent by accident, to the owner
*
* @param _tokenAddress address of token to withdraw
* @param _amount amount of tokens to withdraw, 0 for all
*/
function withdrawTokens(address _tokenAddress, uint256 _amount)
external
override
onlyFactoryOrOwner
{
require(_tokenAddress != address(0), "ZERO_ADDRESS");
IERC20 _token = IERC20(_tokenAddress);
uint256 _balance = _token.balanceOf(address(this));
require(_balance > 0, "NO_TOKEN_BALANCE");
uint256 _amountToWithdraw = (_amount > 0 && _amount <= _balance)
? _amount
: _balance;
SafeERC20.safeTransfer(_token, owner(), _amountToWithdraw);
}
/**
* @dev Updates the start / endblock of the staking window. Also updated the rewards
* per block based on the new timeframe. Use with caution: this function can result
* in unexpected issues, if used during an active staking window.
*
* @param _startBlock start of the staking window
* @param _endBlock end of the staking window
*/
function setStakingWindow(uint256 _startBlock, uint256 _endBlock)
public
virtual
override
onlyFactoryOrOwner
{
require(_endBlock > _startBlock, "INVALID_END_BLOCK");
require(_startBlock > 0, "INVALID_START_BLOCK");
require(_endBlock > 0, "INVALID_END_BLOCK");
// start block cant be in the past
require(_startBlock >= block.number, "INVALID_START_BLOCK");
_poolData.startBlock = _startBlock;
_poolData.endBlock = _endBlock;
// calculate rewards per block
_poolData.rewardsPerBlock = _poolData.totalRewards.div(
_poolData.endBlock.sub(_poolData.startBlock)
);
}
/**
* @dev Updates the whole pool meta data, based on the new pool input object
* This function should be used with caution, as it could result in unexpected
* issues on the calculations. Ideally only used during waiting state
*
* @param _inputData object containing all relevant pool information
**/
function setPoolData(SharedDataTypes.PoolInputData calldata _inputData)
external
virtual
override
onlyFactoryOrOwner
{
// set pool data
_poolData.totalRewards = _inputData.totalRewards;
_poolData.token = _inputData.token;
_poolData.poolType = _inputData.poolType;
_poolData.info = _inputData.tokenInfo;
_totalRewardsLeft = _inputData.totalRewards;
// set staking window and calculate rewards per block
setStakingWindow(_inputData.startBlock, _inputData.endBlock);
emit PoolDataSet(
_poolData.token,
_poolData.totalRewards,
_poolData.startBlock,
_poolData.endBlock
);
}
/* === MODIFIERS === */
modifier onlyRouter() {
require(_msgSender() == address(_router), "FORBIDDEN: ROUTER");
_;
}
modifier onlyRouterOrProAccess(address _user) {
if (_user != address(_router)) {
_checkPro(_user);
}
_;
}
/* === EVENTS === */
event PoolInitiated();
event PoolDataSet(
address rewardToken,
uint256 totalReward,
uint256 startBlock,
uint256 endBlock
);
event RewardClaimed(address indexed user, uint256 amount);
event AllocationPaid(
address indexed user,
address token,
uint256 paidAmount,
uint256 paidAllocation
);
}
// 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;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {SharedDataTypes} from "../../libraries/SharedDataTypes.sol";
interface IUZV1RewardPool {
/* mutating functions */
function claimRewards(address _user) external;
function factory() external returns (address);
function setFactory(address) external;
function transferOwnership(address _newOwner) external;
function pay(address _user, uint256 _amount)
external
returns (uint256 refund);
/* view functions */
// pool specific
function canReceiveRewards() external view returns (bool);
function isPoolActive() external view returns (bool);
function isPayable() external view returns (bool);
function isNative() external view returns (bool);
function getPoolState() external view returns (SharedDataTypes.PoolState);
function getUserPoolStake(address _user)
external
view
returns (SharedDataTypes.PoolStakerUser memory);
function getUserPoolState()
external
view
returns (SharedDataTypes.UserPoolState);
function getPoolType() external view returns (uint8);
function getPoolInfo()
external
view
returns (SharedDataTypes.PoolData memory);
function getAmountOfOpenRewards() external view returns (uint256);
function getStartBlock() external view returns (uint256);
function getEndBlock() external view returns (uint256);
function getTimeWindows() external view returns (uint256[] memory);
function getUserReceiverAddress(address user)
external
view
returns (string memory receiverAddress);
// user specific
function getPendingRewards(address _user)
external
view
returns (uint256 reward);
function getUserInfo(address _user)
external
view
returns (SharedDataTypes.FlatPoolStakerUser memory);
function setNativeAddress(address _user, string calldata _receiver)
external;
function initialize(address _router, address _accessToken) external;
function setPoolData(SharedDataTypes.PoolInputData calldata _inputData)
external;
function withdrawTokens(address _tokenAddress, uint256 _amount) external;
function setStakingWindow(uint256 _startBlock, uint256 _endBlock) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IUZV1RewardPool} from "./pools/IUZV1RewardPool.sol";
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
interface IUZV1Router {
/* view functions */
function getAllUserRewards(address _user)
external
view
returns (address[] memory _pools, uint256[] memory _rewards);
function getAllPools() external view returns (address[] memory);
function getAllTokens()
external
view
returns (
address[] memory tokenList,
uint256[] memory tokenTVLs,
uint256[] memory weights,
uint256 combinedWeight
);
function getAllTokens(uint256 _blocknumber)
external
view
returns (
address[] memory tokenList,
uint256[] memory tokenTVLs,
uint256[] memory weights,
uint256 combinedWeight
);
function getTVLs() external view returns (uint256[] memory _tokenTVLs);
function getTVLs(uint256 _blocknumber)
external
view
returns (uint256[] memory _tokenTVLs);
function getUserTVLShare(address _user, uint256 _precision)
external
view
returns (uint256[] memory);
function getStakingUserData(address _user)
external
view
returns (
address[] memory,
uint256[] memory,
uint256
);
function getTokenWeights()
external
view
returns (uint256[] memory weights, uint256 combinedWeight);
function getUserStakes(address _user)
external
view
returns (uint256[] memory);
function getUserStakes(address _user, uint256 _blocknumber)
external
view
returns (uint256[] memory);
function getUserStakesSnapshots(
address _user,
address _token,
uint256 _startBlock,
uint256 _endBlock
)
external
view
returns (SharedDataTypes.StakeSnapshot[] memory startBlocks);
/* pool view functions */
function canReceiveRewards(address _pool) external view returns (bool);
function isPoolNative(address _pool) external view returns (bool);
function getPoolState(address _pool)
external
view
returns (SharedDataTypes.PoolState);
function getPoolType(address _pool) external view returns (uint8);
function getPoolInfo(address _pool)
external
view
returns (SharedDataTypes.PoolData memory);
function getTimeWindows(address _pool)
external
view
returns (uint256[] memory);
function getPoolUserReceiverAddress(address _pool, address _user)
external
view
returns (string memory receiverAddress);
function getPoolUserInfo(address _pool, address _user)
external
view
returns (SharedDataTypes.FlatPoolStakerUser memory);
function getTotalPriceForPurchaseableTokens(address _pool, address _user)
external
view
returns (uint256);
/* mutating functions */
function claimAllRewards() external;
function claimReward(address _pool) external returns (bool);
function claimRewardsFor(IUZV1RewardPool[] calldata pools) external;
function payRewardAndSetNativeAddressForPool(
address _pool,
uint256 _amount,
string calldata _receiver
) external;
function payRewardPool(address _pool, uint256 _amount) external;
function createNewPool(
uint256 totalRewards,
uint256 startBlock,
uint256 endBlock,
address token,
uint8 poolType,
string memory name,
string memory blockchain,
string memory cAddress
) external returns (address);
function setNativeAddressForPool(address _pool, string calldata _receiver)
external;
/* control functions */
function setFactory(address _factory) external;
function setStaking(address _staking) external;
function emergencyWithdrawTokenFromRouter(address _token, uint256 _amount)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @title UZProAccess
* @author Unizen
* @notice Simple abstract class to add easy checks
* for pro membership access token
**/
abstract contract UZV1ProAccess is
Initializable,
OwnableUpgradeable,
PausableUpgradeable
{
// internal storage of the erc721 token
IERC721 internal _membershipToken;
function initialize(address _token) public virtual initializer {
__Ownable_init();
__Pausable_init();
_setMembershipToken(_token);
}
function membershipToken() public view returns (address) {
return address(_membershipToken);
}
/* === CONTROL FUNCTIONS === */
/**
* @dev pause smart contract
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev unpause smart contract
*/
function unPause() public onlyOwner {
_unpause();
}
/**
* @dev Allows the owner of the contract, to update
* the used membership token
* @param _newToken address of the new erc721 token
**/
function setMembershipToken(address _newToken) public onlyOwner {
_setMembershipToken(_newToken);
}
function _setMembershipToken(address _newToken) internal {
if (_newToken == address(0) && address(_membershipToken) == address(0))
return;
require(_newToken != address(_membershipToken), "SAME_ADDRESS");
_membershipToken = IERC721(_newToken);
}
/**
* @dev Internal function that checks if the users has any
* membership tokens. Reverts, if none is found.
* @param _user address of user to check
**/
function _checkPro(address _user) internal view {
if (address(_membershipToken) != address(0)) {
require(
_membershipToken.balanceOf(_user) > 0,
"FORBIDDEN: PRO_MEMBER"
);
}
}
/* === MODIFIERS === */
modifier onlyPro(address _user) {
_checkPro(_user);
_;
}
/* === EVENTS === */
event MembershipTokenUpdated(address _newTokenAddress);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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);
} | Allows the user to set a custom native address as receiver of rewards as these rewards will be distributed off-chain. _user address of the user, we want to update _receiver string users native address, where rewards will be sent to/ if sender is not router, sender and user have to be identical | function setNativeAddress(address _user, string calldata _receiver)
external
override
onlyRouterOrProAccess(_msgSender())
{
require(isNative() == true, "NO_NATIVE_ADDR_REQ");
require(_user != address(0), "ZERO_ADDRESS");
require(bytes(_receiver).length > 0, "EMPTY_RECEIVER");
if (_msgSender() != address(_router)) {
require(_msgSender() == _user, "FORBIDDEN");
}
_poolStakerUser[_user].nativeAddress = _receiver;
}
| 6,009,672 |
./full_match/42161/0x755188415C88C31B9D1deb1De6aCa17eD998AA22/sources/soluneaArb/interface/IERC721Metadata.sol | ERC-721 Non-Fungible Token Standard, optional metadata extension/ | interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint tokenId) external view returns (string memory);
} | 16,302,425 |
./partial_match/100/0x12A386c9Ad40aBC22D495587c43a925bD09D6f8F/sources/pxv2.sol | make sure the array lengths are all the samepay back previous block price to previous owner | function Buy(uint[] memory block_id_, string memory file_hash_, uint[] memory chunk_id_, uint[] memory block_paid_prices_, string memory attachments, string memory tags) payable public {
require(block_id_.length == chunk_id_.length && block_paid_prices_.length == chunk_id_.length, "block_id_, file_hash_, block_paid_prices_ arrays must be of same length");
require(block_paid_prices_.length == chunk_id_.length);
uint256 remaining_value = msg.value;
for (uint i = 0; i < block_id_.length; i++) {
uint block_id = block_id_[i];
uint256 previous_price = Blocks[block_id].xdai_value;
uint256 paid_price = block_paid_prices_[i];
require(paid_price >= previous_price.mul(BIDDING_PRICE_RATIO_PERCENT).div(100.0), "new paid xDai price must be > previous price * PURCHASE_PRICE_RATIO/100");
balances[Blocks[block_id].owner].available_xdai_balance += previous_price;
require(paid_price >= previous_price, "new paid xDai price must be > MIN_BUY_PRICE for free blocks");
Blocks[block_id].on = true;
}
require(remaining_value >= paid_price, "Must have enough value provided to cover all block_paid_prices");
remaining_value = remaining_value.sub(paid_price);
Blocks[block_id].image_hash = file_hash_;
Blocks[block_id].chunk_id = chunk_id_[i];
Blocks[block_id].status = BlockStatus.VALID;
Blocks[block_id].owner = msg.sender;
Blocks[block_id].xdai_value = msg.value;
used_block_count += 1;
emit _BlockPurchased(block_id, msg.sender, file_hash_, chunk_id_[i], msg.value, attachments, tags);
}
| 16,674,271 |
./full_match/42/0x3682f7350657299edB8d6010792771A81b543b76/sources/contracts/Fundme.sol | $50 What the ETH -> USD conversion rate | function fund() public payable {
uint256 minimumUSD = 50 * 10 ** 18;
require(getConversionRate(msg.value) >= minimumUSD, "You need to spend more ETH !");
}
| 16,233,288 |
pragma solidity ^0.4.24;
import "./safeMath.sol";
import "./NameFilter.sol";
// datasets
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner addr
bytes32 winnerName; // winner name
uint256 amountWon;
uint256 newPot;
uint256 genAmount;
uint256 potAmount; // amount added to the pot
}
struct Player {
address addr; // player addr
bytes32 name;
uint256 names;
uint256 win; // jackpot won
uint256 gen; // key reward won
uint256 aff; // ref reward
uint256 lrnd; // last round played
uint256 laff; // last reffer
}
struct PlayerRounds {
uint256 eth; // Amount of ETH puts into cur round
uint256 keys; // # of keys
uint256 mask;
}
struct Round {
uint256 plyr; // round leader's pID
uint256 end; // ending time timeStamp
bool ended; // is ended
uint256 strt; // starting time
uint256 keys; // number of keys
uint256 eth; // total eth in
uint256 pot; // total jackpot
uint256 mask;
}
}
contract Ape3D {
using SafeMath for *;
using NameFilter for string;
string constant public name = "Ape3D long";
string constant public symbol = "A3D"; // game symbol
// Game data
address public devs; // dev addr
bool public activated_ = false;
uint256 constant private rndInit_ = 24 hours;
uint256 constant private rndInc_ = 60 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public rID_; // roundID
uint256 public registrationFee_ = 10 finney; // register fee
// player data
uint256 public pID_; // Total number of players
mapping(address => uint256) public pIDxAddr_; //(addr => pID)addr to pID
mapping(bytes32 => uint256) public pIDxName_; //(name => pID)name to pID
mapping(uint256 => F3Ddatasets.Player) public plyr_; //(pID => data)pID to player data
mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; //(pID => rID => data
mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_;
// round data
mapping(uint256 => F3Ddatasets.Round) public round_; //(rID => data) rID to round data
mapping(uint256 => uint256) public rndEth_; //(rID => data) rID to round total eth
// emit when a player register a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
uint256 amountPaid,
uint256 timeStamp
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 genAmount
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 genAmount,
uint256 potAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 genAmountf
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 genAmount
);
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// anti-contract
modifier isHuman() {
require(msg.sender == tx.origin);
_;
}
modifier onlyDevs()
{
require(msg.sender == devs, "msg sender is not a dev");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function activate()
public
onlyDevs
{
require(activated_ == false, "Ape3D already activated");
activated_ = true;
// start the first round
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
constructor()
public
{
devs = msg.sender;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePlayer(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
// assigning a new pID to a new player
function determinePlayer(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
// assigning a new pID.
determinePID(msg.sender);
_pID = pIDxAddr_[msg.sender];
bytes32 _name = plyr_[_pID].name;
uint256 _laff = plyr_[_pID].laff;
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// sets "true" for new player
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
// determine player ID
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// return true for new player
return (true);
} else {
return (false);
}
}
// register name using ref's ID
function registerNameXname(string _nameString, bytes32 _affCode)
external
payable
{
require(msg.value >= registrationFee_, "umm..... you have to pay the name fee");
address _addr = msg.sender;
bytes32 _name = NameFilter.nameFilter(_nameString);
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = 0;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer);
}
// core function for register name
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer)
private
{
// check if the name is taken
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// setting up player name and id
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
}
// register fee sends to dev
address(devs).transfer(10 finney);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, msg.value, now);
}
// buy key using refs name
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
external
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePlayer(_eventData_);
// getting player's ID
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last ref code saved
_affID = plyr_[_pID].laff;
} else {
// getting the ref's pID
_affID = pIDxName_[_affCode];
// If the ref's pID is new
if (_affID != plyr_[_pID].laff)
{
// Update
plyr_[_pID].laff = _affID;
}
}
buyCore(_pID, _affID, _eventData_);
}
// use vault to rebuy keys, with name as ref
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
external
{
F3Ddatasets.EventReturns memory _eventData_;
// get player ID
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// getting ref pID
_affID = plyr_[_pID].laff;
} else {
// getting ref pID
_affID = pIDxName_[_affCode];
// If the ref's pID is new
if (_affID != plyr_[_pID].laff)
{
// Update
plyr_[_pID].laff = _affID;
}
}
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.genAmount
);
}
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return (_eventData_);
}
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns (uint256)
{
return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask));
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 10000000000) //0.00000001eth
{
// calculate key received
uint256 _keys = keysRec(round_[_rID].eth,_eth);
// at least one key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leader
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndEth_[_rID] = _eth.add(rndEth_[_rID]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
}
}
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.genAmount,
_eventData_.potAmount
);
}
/**
* @dev distributes eth based on fees to dev and aff
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _devs = (_eth.mul(3)) / 100;
address(devs).transfer(_devs);
_devs = 0;
// distribute share to affiliate
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_devs = _aff;
}
if (_devs > 0)
{
address(devs).transfer(_devs);
_devs = 0;
}
return (_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(67)) / 100;
// calculate pot
uint256 _pot = (_eth.mul(20)) / 100;
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return (_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns (uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
//calculate & return dust
return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local ID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(80)) / 100;
uint256 _gen = 0;
uint256 _res = _pot.sub(_win);
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
return (_eventData_);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is a winner
if (round_[_rID].plyr == _pID)
{
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
(plyr_[_pID].win).add(((round_[_rID].pot).mul(80)) / 100), //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
} else {
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
(plyr_[_pID].win), //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
}
else{
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
}
/**
* @dev returns all current round info needed for front end
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns (uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
_rID, //0
round_[_rID].keys, //1
round_[_rID].end, //2
round_[_rID].strt, //3
round_[_rID].pot, //4
round_[_rID].plyr, // 5
plyr_[round_[_rID].plyr].addr, //6
plyr_[round_[_rID].plyr].name, //7
round_[_rID].eth //8
);
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256,uint256,uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
return((round_[_rID].end),_now, (round_[_rID].end).sub(_now));
// return( );
else
return(0,0,0);
}
/**
* @dev withdraws all of your earnings.
*/
function withdraw()
isActivated()
isHuman()
external
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// pay the player
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.genAmount
);
} else {
// in any other situation
// get their earnings
_eth = withdrawEarnings(_pID);
// pay the player
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns (uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vault
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return (_earnings);
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns (uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
return keysRec(round_[_rID].eth, _eth);
} else {
// rounds over. need keys for new round
return keys(_eth);
}
}
/**
* @dev returns current eth price for X keys.
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns (uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ethRec(round_[_rID].keys + _keys,_keys);
else // rounds over. need price for new round
return eth(_keys);
}
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return (10000*((_eth.mul(1000000000000000000)).sqrt()));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((10000000000).mul(_keys.sq())) / ((1000000000000000000).sq());
}
} | moves any unmasked earnings to gen vault. updates earnings mask/ put in gen vault zero out their earnings by updating mask | function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
| 23,161 |
./full_match/1/0xAef3d07C724CFa27Cd57C5e0a49cE372dA766413/sources/contracts/alloyx/interfaces/IWalletDesk.sol | IWalletDesk AlloyX/ | interface IWalletDesk {
function getWalletUsdcValue(address _poolAddress) external view returns (uint256);
function setUsdcValueForPool(address _vaultAddress, uint256 _amount) external;
pragma solidity ^0.8.7;
}
| 3,134,178 |
./full_match/80001/0x7aA01b23ae3B28f166C44228746CE0b8616a51C4/sources/project:/contracts/Libraries/LibCalculations.sol | Cast to int265 to avoid underflow errors (negative means loan duration has passed) Max payable amount in a cycle NOTE: the last cycle could have less than the calculated payment amount Calculate accrued amount due since last repayment | function calculateOwedAmount(
uint256 principal,
uint256 totalRepaidPrincipal,
uint16 _interestRate,
uint256 _paymentCycleAmount,
uint256 _paymentCycle,
uint256 _lastRepaidTimestamp,
uint256 _timestamp,
uint256 _startTimestamp,
uint256 _loanDuration
)
internal
pure
returns (
uint256 owedPrincipal_,
uint256 duePrincipal_,
uint256 interest_
)
{
owedPrincipal_ = principal - totalRepaidPrincipal;
uint256 interestInAYear = percent(owedPrincipal_, _interestRate);
uint256 owedTime = _timestamp - uint256(_lastRepaidTimestamp);
uint256 owedTimeInHours = owedTime / 3600;
uint256 oneYearInHours = 360 days / 3600;
interest_ = (interestInAYear * owedTimeInHours) / oneYearInHours;
int256 durationLeftOnLoan = int256(uint256(_loanDuration)) -
(int256(_timestamp) - int256(uint256(_startTimestamp)));
uint256 maxCycleOwed = isLastPaymentCycle
? owedPrincipal_ + interest_
: _paymentCycleAmount;
uint256 Amount = (maxCycleOwed * owedTime) / _paymentCycle;
duePrincipal_ = Math.min(Amount - interest_, owedPrincipal_);
}
| 838,841 |
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./AntsToken.sol";
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 ANTS 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");
}
}
}
| (b-a) amountB/(amountA + amountbB) | function updateLockBlock(uint256 _pid, uint256 _amount) internal {
UserInfo storage user = userInfo[_pid][msg.sender];
user.lockBlock = block.number;
user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock);
}
| 12,614,129 |
/*
HABEO - (share around)
----------------------
HABEO is the teoken that will change the way we use crypto.
We'll make it easy to use and easy to understand so everyone can take advantage of it.
This code is fully commented so everyone can learn from it.
The comments are only in english for practical purposes but it should translate very well with Google translate or similar translation
services.
If you have questions about the translation, head out to your Discord Server(https://discord.gg/NA8YnT38sn) and the community will help you.
Check our website for more information: https://www.habeotoken.com
Follow us on Twitter: @HabeoToken
Join our Reddit sub: r/HabeoToken
Check our Youtube channel: https://www.youtube.com/channel/UCmZa_90rxRD08rDiSa7Nh2w
**/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// All these interfaces and cotracts are here to provide the standard functionality for the BEP-20/ERC-20 tokens.
// To look at HABEO's code, start looking at line 385.
interface IERC20 {
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);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Not 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), "Owner is zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "No permission");
require(block.timestamp > _lockTime , "Locked for 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
// function removeLiquidity(
// address tokenA,
// address tokenB,
// uint liquidity,
// uint amountAMin,
// uint amountBMin,
// address to,
// uint deadline
// ) external returns (uint amountA, uint amountB);
// function removeLiquidityETH(
// address token,
// uint liquidity,
// uint amountTokenMin,
// uint amountETHMin,
// address to,
// uint deadline
// ) external returns (uint amountToken, uint amountETH);
// function removeLiquidityWithPermit(
// address tokenA,
// address tokenB,
// uint liquidity,
// uint amountAMin,
// uint amountBMin,
// address to,
// uint deadline,
// bool approveMax, uint8 v, bytes32 r, bytes32 s
// ) external returns (uint amountA, uint amountB);
// function removeLiquidityETHWithPermit(
// address token,
// uint liquidity,
// uint amountTokenMin,
// uint amountETHMin,
// address to,
// uint deadline,
// bool approveMax, uint8 v, bytes32 r, bytes32 s
// ) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
// function removeLiquidityETHSupportingFeeOnTransferTokens(
// address token,
// uint liquidity,
// uint amountTokenMin,
// uint amountETHMin,
// address to,
// uint deadline
// ) external returns (uint amountETH);
// function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
// address token,
// uint liquidity,
// uint amountTokenMin,
// uint amountETHMin,
// address to,
// uint deadline,
// bool approveMax, uint8 v, bytes32 r, bytes32 s
// ) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Habeo is Context, IERC20, Ownable {
// Here's where HABEO code starts //
// For these global variables and structures, we've tried to pack them as much as we could
// to try to save as much gas as possible.
// This link explains some of the what, the why and the how:
// https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e
// Contract structure
struct ContractData{
// Biggest number possible that can be created with uint256.
// We'll use it for reflection calculations.
uint256 MAX;
// Initial supply of tokens
uint256 tokensTotal;
// This does not reflect "the total number of reflections" in a direct way. Instead, it is used
// in the calculations of values to show the right number for tokens+reflections when users
// look at wallet balance.
uint256 reflectionsTotal;
// Maximum transaction size allowed for transfers between wallets.
uint256 maxTxAmount;
// This sets the threshold for the contract to swap and liquify.
// It's inefficient to do it on every transaction so the contract collects
// the liquidity fees and when the contract balance hits numTokensSwapToAddToLiquidity or more,
// it goes through the swap and liquify process on the next transaction.
// This property also sets the number of tokens to swap for BNB.
uint256 numTokensSwapToAddToLiquidity;
// Metadata about the token.
string name;
string symbol;
uint8 decimals;
}
// Create the contract data instance with all the contract's configuration.
ContractData public contractData;
// Wallet structure
struct WalletData {
// For regular wallets, we don't count tokens,
// we coun't reflections so we can calculate new
// balances on the fly to save gas.
uint256 reflectionsOwned;
// For contracts and other interfaces that are excluded from the reflections,
// we do count tokens (and reflections).
uint256 tokensOwned;
// Throttling the ability to swap too quickly.
// HABEO only allows one exchange operation (to swap) every 8 hours.
uint256 lastExchangeOperation;
// When swapping to create liquidity, we need to provide allowance to the
// router so we use this map. It is also needed for any "transfer from" operations users may want to do.
mapping (address => uint256) allowances;
// Accounts marked as true, are not charged taxes nor receive reflections.
// Typical accounts here (at likely only) are the Contract, the Exchanges
// and the burn wallet (after the burn is complete).
bool isExcludedFromTaxAndReflections;
// Did this wallet already acquire tokens at the early distribution?
// Since we only allow for one early distribution per wallet, here's where we set the flag.
bool walletsThatAcquiredAtEarlyDistro;
// This indicates whether this is the address of an exchange or not.
// We need to partiulcarly understand if we are dealing with an Exchange at some points.
bool walletIsExchange;
}
// List of wallets - Anyone having HABEO will have an entry here.
mapping (address => WalletData) private wallets;
// This indicates whether we are in the process of swapping and liquifying or not.
// Basically, this needs to be set to true WHILE we are swapping and liquifying
// so we do not enter into a recursive loop.
bool inSwapAndLiquify;
// Are we still in early distribution mode?
// This will be set to false at the end of early distribution and won't ever change back to true.
bool inEarlyDistro = true;
// 97.5% of the tokens will be burnt over time. This will make the burn wallet the largest holder
// while the burn process is happening and as such, it will eat up more reflections than any other wallet.
// Because of this, the growth of the wallet is accellerated over time until the protocol has burnt 97.5%
// of the circulating tokens. Once this happens and we stop the burning process,
// The burn wallet is then excluded from future reflections and holders will perceive a noticeable increase in
// reflections owned.
bool keepBurning = true;
// Initialization of the PancakeSwap interface objects.
IUniswapV2Router02 public pcsV2Router;
address public pcsV2Pair;
// Wallet address for the devteam.
// This address will be deploying the contract and then, renouncing ownership of it.
// This account exists for two main reasons.
// #1 - allows for addition and removal of exchanges.
// #2 - allows for the dev team to withdraw donations sent to the contract after the early distribution is done.
address private devteam;
//EARLY DISTRO Configs
// Max number of HABEOs to distribute.
// This is the maximum number of HABEOs that the early distribution can exchange.
// The early distribution will be closed at the due date or when having distributed 250,000,000,000,000 HABEO (give or take a few),
// whichever comes first.
uint256 public earlyDistroMaxHABEO = 250000000 * 10**6 * 10**9;
// Expiration time for early distribution: 30 days from contract deployment.
uint256 public earlyDistroDeadline = block.timestamp + 30 days;
// During early distribution, this balance will keep track of the received BNB that will be added to liquidity and
// will be used to pass the value to the initial liquidity addition right when the early distribution ends.
uint256 private liquidityBNB;
// Map to establish # of tokens per BNB at early distribution.
// This exists with the sole purpose of creating a very fair early distribution process.
// Instead of allowing any size request of tokens, we only have 7 different packages offered at early distribution:
// 25, 10, 5, 1, 0.5, 0.2 and 0.1 BNB
// Each package distributes a specific amount of tokens being slightly more beneficial to acquire the 5 BNB worth of packages.
// If everyone acquires 5 BNB worth of the token, we would end up with an initial LP of 2500 BNB. Because there will be a
// number of people acquiring different amounts of token, it is highly possible the initial LP will be larger than 2500 BNB
mapping (uint256 => uint256) public earlyDistroPackages;
// Management
// When new exchanges are added, we push them to this array so we can loop through it
// and remove each exchange from the reflections when running reflections calculations.
// This has to be dynamic because we want to have the ability to add and remove exchanges at any time so
// we can't have a fixed size array.
address[] private newExchanges;
event SwapAndLiquify(uint256 tokensSwapped, uint256 bnbReceived, uint256 tokensIntoLiqudity);
// This is the constructor.
// Constructor code only runs once, at deployment. It basically sets up the contract in the BSC network.
constructor () {
// For those trying to understand this math, look at this article:
// https://weka.medium.com/dividend-bearing-tokens-on-ethereum-42d01c710657
// Original initial supply of tokens = 1,000,000,000,000,000 (that's 15 0s) but we also account for decimals (9).
// Because we are working with 9 decimals, we need to add 9 digits since we cannot use fractional numbers.
// Largest uint256 number that can be created
// Quick way to reference it is to negate 0.
contractData.MAX = ~uint256(0);
// Maximum number of tokens created by the contract
contractData.tokensTotal = 1000000000 * 10**6 * 10**9;
// This is the part of the math that the above mentioned article does a good job at explaining.
contractData.reflectionsTotal = (contractData.MAX - (contractData.MAX % contractData.tokensTotal));
// Max tx amount between accounts is 10,000,000,000 tokens at once.
contractData.maxTxAmount = 10000 * 10**6 * 10**9;
// Once the early distribution has ended, the contract will continue adding to liquidity.
// Instead of adding at every transaction (inefficient), we wait to collect a certain number of tokens
// and then we swap.
// In this case we are waiting to collect 100,000,000 tokens before adding to liquidity.
contractData.numTokensSwapToAddToLiquidity = 100 * 10**6 * 10**9;
// Metadata
contractData.name = "Habeo";
contractData.symbol = "HABEO";
contractData.decimals = 9;
// Set the dev team address variable to the sender address.
// Since we are creating the contract, we are the sender.
// We are also the owner, but this way it is clearer.
// We will be renouncing ownership a few lines below.
devteam = _msgSender();
// Give all the tokens to the contract so the contract can send them to the
// the wallets when the BNB is received.
wallets[address(this)].tokensOwned = contractData.tokensTotal;
wallets[address(this)].reflectionsOwned = contractData.reflectionsTotal;
// Instanciate the router with the valid address
// We keep all of the addresses here or informational purposes but the one used at the time
// of deployment must be the Mainnet V2 (probably in the future, PCS will have more versions).
//0xD99D1c33F9fC3444f8101754aBC46c52416550D1 - Testnet
//0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 - Testnet alternate and currently working well with https://pancake.kiemtienonline360.com/
//0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F - Mainnet V1 router - do not use - here for reference
//0x10ED43C718714eb63d5aA57B78B54704E256024E - Mainnet V2 router - this is the one we deploy with.
pcsV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
// Try to create the pair HABEO/BNB. If it exists, the address for the pair is returned here, if it does not exist
// it is created AND the address returned here.
pcsV2Pair = IUniswapV2Factory(pcsV2Router.factory()).createPair(address(this), pcsV2Router.WETH());
// Remove this contract from fees and reflections.
wallets[address(this)].isExcludedFromTaxAndReflections = true;
// Leave the burn address with fees and reflections. Not needed at this point but
// it helps with understanding how it works. We'll include it when the burn has
// reached the maximum burn expected.
wallets[address(0)].isExcludedFromTaxAndReflections = false;
// Remove original exchange from the reflections.
// We set the address as exchange too.
wallets[pcsV2Pair].isExcludedFromTaxAndReflections = true;
wallets[pcsV2Pair].walletIsExchange = true;
// For those unfamiliar with the way BNB (and most cryptos for that matter) works,
// some quick hints are shared here.
// Please get yourself familiar with these concepts before any other step.
// The units in which operations happen are not 1 BNB. They happen in much smaller fractions.
// The name for the smallest possible unit in BNB is wei.
// 1 BNB = 1 * 10**18 wei (thats 10 to the power of 18).
// When we deal with the coin (BNB in this case) we need to do it in multiples of wei.
// So, you'll see a lot of 0s or multiplications and exponentiations happening along the code
// to make the numbers easier to understand.
// There are not many instances in the code where we need to calculate 25,10,5,1,0.5,0.2 and 0.1 BNB
// so we use literals in order to save storage.
// We are assigning token distribution depending on the value of BNB that is sent at early distribution.
// For each level down from 5 BNB, you receive 10% fewer tokens, except for 0.5, 0.2 and 0.1 BNB since
// percentage does not decrease after 0.5.
// 0.5 BNB, 0.2 BNB amd 0.1 BNB receive the same proportional number of tokens.
// For each level above 5 BNB you receive 10% fewer tokens. This way we encourage to acquire a good number
// of tokens and discourage becoming a whale.
// For 5 BNB you get 500,000,000,000 tokens - swapping value in BNB per token = 0.00000000001000 BNB
// At the time of this writing, BNB is around $350 or so FIAT value for each token at this level would be
// around $0.0000000035
// For 25 BNB 1,806,250,000,000 tokens - swapping value in BNB per token = 0.000000000013841 BNB (27.75% fewer compared to 5 BNB)
earlyDistroPackages[25 * 10**18] = 1806250 * 10**6 * 10**9;
// For 10 BNB you get 850,000,000,000 tokens - swapping value in BNB per token = 0.000000000011765 BNB (15% fewer compared to 5 BNB)
earlyDistroPackages[10 * 10**18] = 850000 * 10**6 * 10**9;
// For 5 BNB you get 500,000,000,000 tokens - swapping value in BNB per token = 0.00000000001000 BNB (Sweet spot)
earlyDistroPackages[5 * 10**18] = 500000 * 10**6 * 10**9;
// For 1 BNB you get 90,000,000,000 tokens - swapping value in BNB per token = 0.00000000001111 BNB (10% fewer compared to 5 BNB)
earlyDistroPackages[1 * 10**18] = 90000 * 10**6 * 10**9;
// For 0.5 BNB you get 40,500,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (19% fewer compared to 5 BNB)
earlyDistroPackages[5 * 10**17] = 40500 * 10**6 * 10**9;
// For 0.2 BNB you get 16,200,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (Same proportion to 0.5 BNB)
earlyDistroPackages[2 * 10**17] = 16200 * 10**6 * 10**9;
// For 0.1 BNB you get 8,100,000,000 tokens - swapping value in BNB per token = 0.00000000001234 BNB (Same proportion to 0.2 BNB)
earlyDistroPackages[1 * 10**17] = 8100 * 10**6 * 10**9;
// For the tokenomics these will present us with the following numbers:
// If all early distribution tokens are distributed at 5 BNB:
// 500 operations of 5 BNB each x 500,000,000,000 HABEO each = 2500 BNB collected / 250,000,000,000,000 tokens distributed.
// 2500 BNB / 250,000,000,000,000 HABEO Liquidity
// 500,000,000,000,000 Total tokens in circulation at start.
// 500,000,000,000,000 Total tokens burnt right at the close of early distribution.
// 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt
// and 25,000,000,000,000 total in circulation.
// If all early distribution tokens are distributed at 0.1 BNB:
// 30,864 operations of 0.1 BNB each x 8,100,000,000 HABEO each = ~3,086 BNB collected / 250,000,000,000,000 tokens distributed
// 3,086 BNB / 250,000,000,000,000 HABEO Liquidity
// 500,000,000,000,000 total tokens in circulation at start
// 500,000,000,000,000 Total tokens burnt right at the close of early distribution.
// 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt
// and 25,000,000,000,000 total in circulation.
// If all early distribution tokens are distributed at 25 BNB:
// 138 operations of 25 BNB each x 1,806,250,000,000 HABEO each = ~3,460 BNB collected / 250,000,000,000,000 tokens distributed
// 3,460 BNB / 250,000,000,000,000 HABEO Liquidity
// 500,000,000,000,000 total tokens in circulation at start
// 500,000,000,000,000 Total tokens burnt right at the close of early distribution.
// 475,000,000,000,000 burnt over time to get to 975,000,000,000,000 tokens burnt
// and 25,000,000,000,000 total in circulation.
// The difference between all three case scenarios is that in the second and third one, there will be more BNB in the
// liquidity pool right after the early distribution ends.
// The most likely case will be a mixture of all options which will bring the amount of BNB to somewhere in between.
// This is where we renounce ownership.
// The function is defined under the Owenable class if you want to see the details.
renounceOwnership();
// We emit tokenstotal so we do not need to calculate from reflection.
// At construction they are the same so we emit tokensTotal which is cheaper in gas
emit Transfer(address(0), _msgSender(), contractData.tokensTotal);
}
// Constructor ends here. The rest of the code are functions that can be called externally or internally.
// External functions are ONLY called externally.
// Public functions are called EITHER internally or externally.
// Internal functions are only accessible from the contract or any contracts derived from this contract.
// Private functions can only be called from within the contract.
// For HABEO, there are no unused functions. All of them are used somehow.
// The receive() function is called when someone sends BNB to the contract and when the swap and liquify
// process receives BNB to add to liquidity.
// The withdrawBNBDonationsToDevTeam() can be called by anyone and it will only execute AFTER early distribution
// The only thing it does is to withdraw whatever amount of BNB is in the contract (donations) and send it to the dev wallet.
// The addRemoveExchange() function can only be called by the developeraccount and is used to add / remove
// exchange addresses. This is needed so we can add exchanges that list HABEO on the fly and remove addresses
// when exchanges update their contracts.
// The rest of the functions are explained near the function code.
// This function starts as the receiver of BNB for the early distribution and then
// is used for the contract to recieve excess BNB from pcsV2Router when swaping.
// Once the early distribution is done, donations to the devteam can be sent here too.
receive() external payable {
// To save gas, we avoid using require statements every chance we have.
// For instance, instead of checking if the earlyDistroMaxBNB limit is already reached,
// we let Solidity detect the overflow and cause an exception.
// the exception (negative number) will cause a revert.
// This will generate a generic "revert" fail message for the user but it saves gas to the user too.
// As all exceptions and requires will eat up the gas anyways, it is better to make it cheaper to the user in gas.
if (!inEarlyDistro || inSwapAndLiquify) {
// We only arrive here if early distribution is done and someone donates to the dev team OR
// if the router sends us swap excess.
// We emit so the transfer is logged.
emit Transfer(_msgSender(), address(this), msg.value);
} else if (_msgSender() != address(pcsV2Router)) {
// If we are at the due date or earlyDistroMaxBNB is reached,
// we honor the last request even if it is after the established date
// or if the earlyDistroMaxHABEO has been reached.
// This does not affect the balance of tokens, BNB and burns at all so it's easier to
// just do it and reward the last person that tried to get tokens at early distribution.
// worst case scenario we'll be sending an extra 25 BNB in tokens, best case scenario we'll
// be sending extra 0.1 BNB in tokens.
// Either way, it should improve pricing at the exchange.
// We do need to check if the value sent aligns with one of the allowed amounts.
// If we get 0 here, an invalid amount of BNB was sent so we revert.
uint256 tokensAmount = earlyDistroPackages[msg.value];
require (tokensAmount > 0 , "Wrong request amount");
// If someone wants to sneak a second request from a wallet, we revert.
require (!wallets[_msgSender()].walletsThatAcquiredAtEarlyDistro, "Only 1 per wallet");
// We do want to use a variable as a temporary holder of the value to prevent re-entry attacks.
uint256 amountBNB = msg.value;
// Add the amount to the liquidity holder.
liquidityBNB += amountBNB;
// Remove the tokens from the contract.
wallets[address(this)].tokensOwned -= tokensAmount;
// Remove the reflections from the contract.
// We could be using some of the existing functions to calculate rather than doing the math here.
// However, it is saving gas to do it this way.
wallets[address(this)].reflectionsOwned -= tokensAmount * (contractData.reflectionsTotal/contractData.tokensTotal);
// Add the wallet to the list of wallets that have acquired tokens at the early distribution.
wallets[_msgSender()].walletsThatAcquiredAtEarlyDistro = true;
// Give the tokens to the wallet in reflections form.
wallets[_msgSender()].reflectionsOwned += tokensAmount * (contractData.reflectionsTotal/contractData.tokensTotal);
// Emit the event so the transfer is logged.
emit Transfer(address(this), _msgSender(), tokensAmount);
// Check to see if we have reached the total number of HABEOs at the early distribution or the earlyDistroDeadline.
if (earlyDistroMaxHABEO > tokensAmount && block.timestamp < earlyDistroDeadline){
// If not, just deduct the new amount.
earlyDistroMaxHABEO -= tokensAmount;
} else if (earlyDistroMaxHABEO <= tokensAmount){
// If we did, then ensure the value for earlyDistroMaxHABEO is 0 and close the early distribution.
earlyDistroMaxHABEO = 0;
closeTheEarlyDistro();
inEarlyDistro = false;
}
}
}
// Here is where we close the early distribution
function closeTheEarlyDistro() internal {
// Initial burn number after early distribution. This is the number of tokens to be burnt right after early distribution.
// both in tokens and in reflections as the wallet is not excluded from reflections until we reach
// the max burn.
uint256 tInitialBurn = 500000000 * 10**6 * 10**9;
uint256 rInitialBurn = tInitialBurn * (contractData.reflectionsTotal/contractData.tokensTotal);
// We substract the burnt tokens from the contract.
wallets[address(this)].tokensOwned -= tInitialBurn;
// We substract the burn reflections from the contract.
wallets[address(this)].reflectionsOwned -= rInitialBurn;
// We move the tokens and reflections to the burn wallet.
wallets[address(0)].tokensOwned = tInitialBurn;
wallets[address(0)].reflectionsOwned = rInitialBurn;
// We emit the transfer so it is logged.
emit Transfer(address(this), address(0), tInitialBurn);
//We need to set the flag on so we can process the liquification
inSwapAndLiquify = true;
// Add all the tokens in the contract and all the BNBs as a pair.
// Instead of calling swap and liquify, we can call addLiquidity directly because,
// we already have the BNB so there's no need for swapping.
// We provide all the remaining tokens in the contract and all the liquidity collected.
addLiquidity(wallets[address(this)].tokensOwned, liquidityBNB, true);
}
// All these are the functions that show metadata upon request.
// they are all external because they are usually called by wallets
// and exchanges to show token data.
function name() external view returns (string memory) {
return contractData.name;
}
function symbol() external view returns (string memory) {
return contractData.symbol;
}
function decimals() external view returns (uint8) {
return contractData.decimals;
}
function totalSupply() external view override returns (uint256) {
return contractData.tokensTotal;
}
// Simply returns the value in tTokens for the requested account
// If the account is excluded, it simply returns the value.
// If the account is not excluded, then we need to calculate the token value from the reflections value.
function balanceOf(address account) external view override returns (uint256) {
if (wallets[account].isExcludedFromTaxAndReflections) return wallets[account].tokensOwned;
return tokensFromReflections(wallets[account].reflectionsOwned);
}
// This function shows what the allowance is for a certain pair of addresses.
function allowance(address owner, address spender) external view override returns (uint256) {
return wallets[owner].allowances[spender];
}
// Transfer and approve are called by wallets/exchanges to initiate a transfer.
// The approve function is the one that provides allowance to the exchanges to operate
// on the user's behalf.
// It can also be called manually by an experienced user to set up someone else to spend
// tokens on the original user's behalf.
// Of course the only account that can allow an approve call is the user allowing someone
// else to spend on their behalf.
// This is the point of entry for the transfer requests.
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
// This is the entry point for the approve function.
// This enables an address to spend a certain amount of tokens on behalf of another address.
// Basically, provides allowances to addresses.
// This is used quite a bit at swap time and gives users the chance to allow others to spend on their behalf.
// This is a requirement for DeFi exchanges like Pancakeswap. They ask for your approval to do this before you can swap.
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount,true);
return true;
}
// User may want to decrease the allowance provided to another account.
// This is the point of entry for that.
// This is not a common function to have. We provide it because we've seen some exchanges
// (like PancakeSwap for instance) that sometimes try to get a wide range approval all at once.
// If the user decides later that wants to lower this allowance, this is the function to call.
// For a user to call this, the user needs to have a little bit more advanced knowledge.
function decreaseAllowance(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount,false);
return true;
}
// This is the actual worker for the approve function.
// This can only be called from this contract.
function _approve(address allower, address spender, uint256 amount, bool incrementDecrement) private {
// incrementDecrement determines if this is an increase or a decrease request.
// If we are incrementing the allowance, we add to it.
// If we are decrementing, we decrement and if we don't have enough, we set to 0.
if(incrementDecrement){
if (amount >= contractData.MAX - wallets[allower].allowances[spender]){
wallets[allower].allowances[spender] = contractData.MAX;
} else {
wallets[allower].allowances[spender] += amount;
}
} else if (wallets[allower].allowances[spender] >= amount){
wallets[allower].allowances[spender] -= amount;
} else {
wallets[allower].allowances[spender] = 0;
}
// We emit the event to log it.
emit Approval(allower, spender, amount);
}
// General transfer function to send from one account to another.
// This is what the allowance is for when a user authorizes another user to spend on behalf.
// This is a standard BEP-20/ERC-20 function.
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
// First we try to decrease the allowance.
// If we do not have enough allowance we revert through the exception.
wallets[sender].allowances[_msgSender()] -= amount;
// If we have the allowance, we transfer.
_transfer(sender, recipient, amount);
return true;
}
// This function returns the number of tokens owned by providing the current number of reflections
// it is only used internally a couple of times but one of those is the balanceOf function which is
// called continuously by the exchanges and wallets.
function tokensFromReflections(uint256 reflectionsAmount) private view returns(uint256) {
// First we get the current rate of reflections vs tokens.
// Then we divide by the rate.
// The getRate function spins up the currentsupply calculation which is complex and spends gas.
uint256 currentRate = getRate();
return reflectionsAmount / currentRate;
}
// This is the function used at transfer time that returns various values that are needed for a correct
// distribution of tokens.
// The amount to provide is the number of real tokens and the function returns values in both reflection and token.
// We need this translation because of reflection.
// This is a very gas expensive function.
function getValues(uint256 tAmount, uint256 tax) private view returns (uint256, uint256, uint256, uint256, uint256) {
// We need to find out the t values.
(uint256 tTransferAmount, uint256 tFee) = getTValues(tAmount, tax);
// And we need to out the r values.
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = getRValues(tAmount, tFee, getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
// This is a spinoff from the getValues function and it returns the token part of the values
function getTValues(uint256 tAmount, uint256 tax) private pure returns (uint256, uint256) {
// Tax is a percentage so we calculate the t value of the fees.
uint256 tFee = tAmount * tax / 10**2;
// transferAmount is tokenAmount minus tax minus liq (to save gas we use the same
// variable since rate for tax = liq rate)
uint256 tTransferAmount = tAmount - tFee - tFee;
return (tTransferAmount, tFee);
}
// This is a spinoff from the getValues function and it returns the reflections part of the values
function getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
// convert tokens to reflections
uint256 rAmount = tAmount * currentRate;
// do the same for the fees
uint256 rFee = tFee * currentRate;
// now calculate the transfer amount in reflections too.
// substract fee two times because of liq AND reflections.
uint256 rTransferAmount = rAmount - rFee - rFee;
return (rAmount, rTransferAmount, rFee);
}
// This function calculates and returns the rate of conversion between reflections and tokens.
// Notice that it calls getCurrentSupply which is an expensive function.
function getRate() private view returns(uint256) {
(uint256 reflectionsSupply, uint256 tokensSupply) = getCurrentSupply();
return reflectionsSupply / tokensSupply;
}
// We calculate supply as follows:
// - We start with the total for tokens and reflections
// (maximum number of tokens and reflections minus reflections fees that
// have been removed over time because of the reflection distribution process)
// - We remove any tokens and reflections that are owned by the excluded accounts from that supply.
// - We then return those totals which are the current supply for tokens and reflecions
function getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = contractData.reflectionsTotal;
uint256 tSupply = contractData.tokensTotal;
// We do need to check if we are in early distribution because we do not apply reflections at early distribution.
// In this case we return totals.
// If this was not here, then it would mess balances because the contract still owns all of the
// tokens that have yet to be acquired.
if (inEarlyDistro){
return (contractData.reflectionsTotal, contractData.tokensTotal);
}
// This is exclusively for precaution. If for whatever reason the numbers don't add up,
// go back to the basics. This is the least invasive thing to do.
if (rSupply < contractData.reflectionsTotal / contractData.tokensTotal) return (contractData.reflectionsTotal, contractData.tokensTotal);
// This is expensive.
// This loop goes through all of the added exchanges and, as they are excluded,
// removes the r and t values belonging to them.
for (uint256 i = 0; i < newExchanges.length; i++) {
rSupply -= wallets[newExchanges[i]].reflectionsOwned;
tSupply -= wallets[newExchanges[i]].tokensOwned;
}
// We know these are already excluded so we make the above loop shorter.
tSupply = tSupply - wallets[pcsV2Pair].tokensOwned - wallets[address(this)].tokensOwned;
rSupply = rSupply - wallets[pcsV2Pair].reflectionsOwned - wallets[address(this)].reflectionsOwned;
// Once we are done burning, we start excluding the burning address form the supply.
if (!keepBurning){
tSupply -= wallets[address(0)].tokensOwned;
rSupply -= wallets[address(0)].reflectionsOwned;
}
return (rSupply, tSupply);
}
// This is the worker transfer function
// It is a wrapper for the transfer functions that are specific for each scenario
// General calculations happen here.
function _transfer(address from, address to, uint256 amount) private {
uint256 contractTokenBalance = 0;
// During early distribution, only transactions from the contract are allowed.
// This is so the contract can distribute the tokens and add to the liquidity pool WHILE
// no reflections or taxing happens.
if (inEarlyDistro){
if(from != address(this)){
revert("Cannot transfer during early distribution");
}
} else {
// We only check this if we are not in early distribution anymore.
// Is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
contractTokenBalance = wallets[address(this)].tokensOwned;
}
// Between regular accounts, there's a max transfer size.
// However, anyone can swap as much as they want. Swapping large numbers pays higher taxes.
// Also the contract and the burn wallet can transfer as much as they want.
if((!wallets[from].walletIsExchange && !wallets[to].walletIsExchange)
|| (!wallets[from].isExcludedFromTaxAndReflections
&& !wallets[to].isExcludedFromTaxAndReflections)){
require(amount <= contractData.maxTxAmount, "Above Transfer Limit");
}
// Make sure the request is not coming from PCS so we prevent a circular event.
// Saving some variable declaration by setting the contractBalance to the numTokensSwapToAddToLiquidity
// so we can swap a fixed ammount of tokens.
if (from != pcsV2Pair && (contractTokenBalance >= contractData.numTokensSwapToAddToLiquidity)
&& !inSwapAndLiquify) {
contractTokenBalance = contractData.numTokensSwapToAddToLiquidity;
// Swap and add liquidity
swapAndLiquify(contractTokenBalance);
}
// If we are still burning it's because we did not hit 975,000,000,000,000 burnt yet,
// check and see if we did hit that mark. If we did, we stop burning, convert the
// reflections into tokens and move the
// 0x address to excluded so it does not receive any more reflections.
if (keepBurning){
// We need to check the burn wallet balance.
// Lifetime max number of tokens to burn.
// Amazingly, it is cheaper to run the math here than to have a stored global with the value.
// Both for deployment and exec.
// Max lifetime burn = 975,000,000,000,000
if (wallets[address(0)].tokensOwned >= (975000000 * 10**6 * 10**9)){
// Stop the burn
keepBurning = false;
// Convert 0x wallet into an excluded address so it does not receive any more reflections
wallets[address(0)].isExcludedFromTaxAndReflections = true;
}
}
// Initiate transfer. Tax will be charged later.
tokenTransfer(from,to,amount);
}
// This is where we start the process to provide liquidity on a regular basis.
// We first swap half of the tokens for BNB.
// Then, we add liquidity putting together the remaining half of the tokens and the swapped BNB as pair.
// There will be a very small leftover that goes into the contract address.
// The reason to do it like this is that liquidity needs to be added in a balanced way.
// If the new liquidity was not balanced, then if would affect swap value noticeably
// (the exchange does not allow this anyways).
// So, we see how much BNB we can obtain with half of the tokens. Then, we have the remaining half of the tokens
// that evidently are worth pretty much the amount of BNB that we've received for the initial half.
// Putting these two together to add liquidity gives us a huge chance of having a pretty accurate calculation.
// Nevertheless, as the amounts will not be perfect, the small leftovers are returned to the contract.
function swapAndLiquify(uint256 contractTokenBalance) private {
// We must raise a flag to recognize that we have started a swap.
inSwapAndLiquify = true;
// If we are still burning, this is where we take some tokens to burn them
if (keepBurning){
// We liquify 90% of the fees
// We burn 10% of the fees
// We divide contractTokenBalance by 10 so we can burn 10%
uint256 burnPile = contractTokenBalance / 10;
// If we substract 10% from 100%, we have 90%.
// we'll use this 90% to liquify.
contractTokenBalance -= burnPile;
// What's the reflections amount for the burned tokens?
(uint256 rAmount, , , , ) = getValues(burnPile, 0);
// Burn the tokens.
wallets[address(0)].reflectionsOwned += rAmount;
// even though the burn wallet is not excluded from reflections yet,
// we still add the tokens to keep it up to date.
wallets[address(0)].tokensOwned += burnPile;
//Emit a transfer to show the movement.
emit Transfer(address(this), address(0), burnPile);
}
// Now that we have the 90% to work with, we split the contract balance into halves.
uint256 half = contractTokenBalance / 2;
// Capture the contract's current BNB balance.
// This is so that we can capture exactly the amount of BNB that the
// swap creates, and not make the liquidity event include any BNB that
// had been left over or manually sent to the contract.
uint256 initialBalance = address(this).balance;
// Swap half of the tokens for BNB.
swapTokensForBNB(half);
// How much BNB did we just swap into?
// We have to do this so we can maintain the balance as close as possible in the LP.
uint256 bnbSwapAmmount = address(this).balance - initialBalance;
// Get the contract to add liquidity to PCS
addLiquidity(half, bnbSwapAmmount,false);
emit SwapAndLiquify(half, bnbSwapAmmount, half);
}
// This is where we get the tokens swapped for BNB.
function swapTokensForBNB(uint256 tokenAmount) private {
// Create the array to pass as the pair token/weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pcsV2Router.WETH();
// Since the router will be using tokens on behalf of the contract,
// we need to get an allowance.
_approve(address(this), address(pcsV2Router), tokenAmount,true);
// Make the swap happen and set the contract as the receiver of any leftover.
pcsV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp + 10 seconds
);
}
// This is where we add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount, bool fromEarlyDistro) private {
// Again, we need to make sure the router can spend the tokens on behalf of the contract.
// We save some gas by adding allowance directly instead of going through approve.
// _approve(address(this), address(pcsV2Router), tokenAmount, true);
wallets[address(this)].allowances[address(pcsV2Router)] += tokenAmount;
// We need to check whether we arrived here through the swapandliquify function or directly
// from the early distribution end event.
if(fromEarlyDistro){
// If we got here from the early distribution, we clear the variable containing the liquidity amount
// since we have passed it now as tokenAmount with the call.
liquidityBNB = 0;
}
// We add the liquidity and lock the CAKE-LP forever.
pcsV2Router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0,
0,
// Sending the CAKE tokens to the burn wallet means
// they are not recoverable and the liquidity is locked forever
address(0),
block.timestamp + 10 seconds
);
// Turn the flag off for swapping.
inSwapAndLiquify = false;
}
// This method is responsible for deciding what route to take with regards to fees
function tokenTransfer(address sender, address recipient, uint256 amount) private {
if (wallets[sender].walletIsExchange) {
// This should only take the basic tax ammount since it's someone obtaining HABEO
// it should not however take fees if recipient is excluded.
transferFromExchange(sender, recipient, amount);
} else if (wallets[recipient].walletIsExchange) {
// We need to check if the owner or contract are sending to LP, in which case we do not take fees.
// If it is not the case, then this is a regular account swapping. take taxes accordingly
transferToExchange(sender, recipient, amount);
} else if (wallets[sender].isExcludedFromTaxAndReflections || wallets[recipient].isExcludedFromTaxAndReflections) {
// This is excluded/excluded transactions and not exchanges are involved, no fees.
transferWithExcluded(sender, recipient, amount);
} else {
// If nothing else, default to standard.
// These are two regular accounts transferring tokens from one to the other.
// Low fees.
transferStandard(sender, recipient, amount);
}
}
// This method is a helper to calculate the tax rate that an operation incurs.
// This is only triggered when the TO is an exchange since that's a swapping out operation.
// The rate is based on the percentage of account balance being transferred.
function calculateTaxAndLiquidityBasedOnTxPercentage(uint256 senderBalance,uint256 amount) private pure returns (uint256){
// Minimum tax.
uint256 tax = 1;
// Percentage of amount over senderBalance.
uint256 pctSwappedOut = amount * 100 / senderBalance;
// Remember that this only calculates the rate.
// This rate applies to both charges, the reflection fee and the liquidity.
// So, percentages taken from the txs are 2,4,6,8,10,20,30,40,50,60 respectively.
if (pctSwappedOut <= 1) {
tax = 1;
} else if (pctSwappedOut <= 2) {
tax = 2;
} else if (pctSwappedOut <= 3) {
tax = 3;
} else if (pctSwappedOut <= 4) {
tax = 4;
} else if (pctSwappedOut <= 5) {
tax = 5;
} else if (pctSwappedOut <= 10) {
tax = 10;
} else if (pctSwappedOut <= 20) {
tax = 15;
} else if (pctSwappedOut <= 40) {
tax = 20;
} else if (pctSwappedOut <= 75) {
tax = 25;
} else if (pctSwappedOut <= 100) {
tax = 30;
}
return (tax);
}
// Standard transactions are the easiest.
// Two regular wallets trading tokens.
// Very low fee. 2% total. (1% tax rate)
function transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 tTransferAmount;
uint256 tFee;
// Standard transfers have a tax rate of 1 so we hardcode it to save gas.
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 1);
// Remove the reflections from the sender
wallets[sender].reflectionsOwned -= rAmount;
// Add the reflections (minus taxes) to the recipient.
wallets[recipient].reflectionsOwned += rTransferAmount;
// Now, take care of the liquidity and fees
takeCareOfLiquidityAndFees(rFee, tFee);
// Show the transaction to the world.
emit Transfer(sender, recipient, tTransferAmount);
}
// This other route means we are sending tokens to an exchange
// This could be either a swap or liquidity provision.
// If it's a swap, high tax. if it is LP, no tax.
function transferToExchange(address sender, address recipient, uint256 tAmount) private {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 tTransferAmount;
uint256 tFee;
// We have to do this (getValues) two times, the first one is to get the ramount so we can
// understand what percentage of the wallet is being affected. We do this with a tax of 0 so
// no fees are deducted.
// We do it outside the "If then" so we can use the resulting values as the first instance of the if or at the else.
// We do the second one, after we've calculated the taxes for this transaction.
// This time around, taxes are charged.
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0);
// Is this a regular wallet?
if (!wallets[sender].isExcludedFromTaxAndReflections){
// Regular accounts can't swap more often than once every 8 hours.
require (wallets[sender].lastExchangeOperation <= block.timestamp - 8 hours, "Too soon");
// Calculate the tax rate
(uint256 taxRate) = calculateTaxAndLiquidityBasedOnTxPercentage(wallets[sender].reflectionsOwned, rAmount);
// Now we need to calculate the transfer and fees/liqs with the updated tax values
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, taxRate);
// We remove the reflections from the sender. All of the amount.
wallets[sender].reflectionsOwned -= rAmount;
// We add the reflections to the exchange. Just the transfer amount.
wallets[recipient].reflectionsOwned += rTransferAmount;
// We add the tokens to the exchange. Just the transfer amount.
wallets[recipient].tokensOwned += tTransferAmount;
// We update the timestamp so the wallet cannot operate until the next window.
wallets[sender].lastExchangeOperation = block.timestamp;
} else {
// If this is an excluded wallet, then it's simpler as they are not charged taxes.
// Take tokens from sender.
wallets[sender].tokensOwned -= tAmount;
// Take tokens from sender.
wallets[sender].reflectionsOwned -= rAmount;
// Add the tokens to the exchange.
wallets[recipient].tokensOwned += tTransferAmount;
// We add the reflections to the exchange. Just the transfer amount.
wallets[recipient].reflectionsOwned += rTransferAmount;
}
// Now, take care of the liquidity and fees
takeCareOfLiquidityAndFees(rFee, tFee);
// Show the transaction to the world.
emit Transfer(sender, recipient, tTransferAmount);
}
// If an excluded address is reciving tokens from PCS then, no fees.
// This could be being done to manage LP or something to that extent.
// If the recipient is a regular account, then they are obtaining tokens so, low fees.
function transferFromExchange(address sender, address recipient, uint256 tAmount) private {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 tTransferAmount;
uint256 tFee;
// Is this an excluded account?
if (wallets[recipient].isExcludedFromTaxAndReflections){
// No tax so 0 passed.
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0);
// Remove the tokens from the exchange wallet.
wallets[sender].tokensOwned -= tAmount;
// Remove the reflections from the exchange wallet.
wallets[sender].reflectionsOwned -= rAmount;
// Add the tokens to the recipient.
wallets[recipient].tokensOwned += tTransferAmount;
// Add the reflections to the recipient.
wallets[recipient].reflectionsOwned += rTransferAmount;
} else {
// This is a regular account getting tokens.
// Regular accounts can't swap more often than once every 8 hours.
require (wallets[recipient].lastExchangeOperation <= block.timestamp - 8 hours, "Too soon");
// Minimal tax of 1%.
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 1);
// Remove the tokens from the exchange.
wallets[sender].tokensOwned -= tAmount;
// Remove the tokens from the exchange.
wallets[sender].reflectionsOwned -= rAmount;
// Add the reflections to the recipient's wallet.
wallets[recipient].reflectionsOwned += rTransferAmount;
// We update the timestamp so the wallet cannot operate until the next window.
wallets[recipient].lastExchangeOperation = block.timestamp;
}
// Now, take care of the liquidity and fees
takeCareOfLiquidityAndFees(rFee, tFee);
// Show the transaction to the world.
emit Transfer(sender, recipient, tTransferAmount);
}
// We are dealing with either, or both accounts being excluded but with no exanches involved.
function transferWithExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 tTransferAmount;
uint256 tFee;
// No taxes when working with excluded accounts
(rAmount, rTransferAmount, rFee, tTransferAmount, tFee) = getValues(tAmount, 0);
//These apply to all cases
// Remove reflections from sender.
wallets[sender].reflectionsOwned -= rAmount;
// Add reflections to recipient.
wallets[recipient].reflectionsOwned += rTransferAmount;
// If both are excluded.
if (wallets[sender].isExcludedFromTaxAndReflections && wallets[recipient].isExcludedFromTaxAndReflections){
// Remove tokens from sender.
wallets[sender].tokensOwned -= tAmount;
// Add tokens to recipient.
wallets[recipient].tokensOwned += tTransferAmount;
} else if(wallets[sender].isExcludedFromTaxAndReflections){
// Only the sender is excluded so, take tokens from sender.
wallets[sender].tokensOwned -= tAmount;
} else {
// Add tokens to recipient.
wallets[recipient].tokensOwned += tTransferAmount;
}
// Now, take care of the liquidity and fees
takeCareOfLiquidityAndFees(rFee, tFee);
// Show the transaction to the world.
emit Transfer(sender, recipient, tTransferAmount);
}
function takeCareOfLiquidityAndFees(uint256 refFee, uint256 tokFee) private {
// Add the liquidity tokens to the tokens owned by the contract.
// Liquidity and fees have the same value so we only use a generic fee that we can apply both for
// liquidity and tax/reflections.
wallets[address(this)].tokensOwned += tokFee;
wallets[address(this)].reflectionsOwned += refFee;
// Remove the fee from the reflections totals (this is how distribution happens).
contractData.reflectionsTotal -= refFee;
}
// We are opening anyone to donate BNB to the dev team by sending it to the contract.
// Together with the donations, there will be a very small amount of leftover BNB from
// the swaps that will accumulate over time.
// The reason this leftover is in the contract is that after swap and liq, there's always a small
// rounding amount because the exchange could never be exact.
// This keeps accummulating in the contract address and it is inevitable because of the way liquidity pools work.
// The ammount each time is minimal (a few dollar cents at current BNB value) so it does not
// affect trading or liq at all.
// However, it is a waste to leave this in the contract accumulating over time.
// So, we've added a function that when called by anyone, sends the accummulated BNB to the devteam's wallet.
// As ownership is renounced, the BNB would get locked and lost forever if this function did not exist.
// This function does not work until the early distribution is done so devs can't collect BNB from it.
function withdrawBNBDonationsToDevTeam() external{
// If we are in early distribution or swapping, leave.
if (!inEarlyDistro && !inSwapAndLiquify){
// Get the balance.
uint256 amount = address(this).balance;
// Send the BNB to the devs wallet.
payable(devteam).transfer(amount);
// Let everyone know this happened.
emit Transfer(address(this), address(devteam), amount);
}
}
// This function is only callable by dev team.
// The use for this is to add or remove an exchange account.
// To add, we simply append at the end of the array.
// To remove, we need to go through a loop, find the account, remove it,
// move the last account into the slot of the removed one and then, shorten the array by 1.
// We also set the right flags on the account and convert/remove tokens.
function addRemoveExchange(address account, bool addRemove) external {
// If the devteam did not call this, leave.
if (msg.sender == devteam){
// If this flag is true then, we are adding an exchange.
if (addRemove){
// if it has any reflections on it we get the token value for them.
wallets[account].tokensOwned = tokensFromReflections(wallets[account].reflectionsOwned);
// This wallet is now an exchange.
wallets[account].walletIsExchange = true;
// Exclude the wallet from taxes and reflections.
wallets[account].isExcludedFromTaxAndReflections = true;
// Add the account to the newExchanges array for later looping when needed.
newExchanges.push(account);
} else {
// We are removing an exchange.
// We need to loop through the array until we find the affected account.
for (uint256 i = 0; i < newExchanges.length; i++) {
// If we find it, we remove it.
if (newExchanges[i] == account) {
// We move the last address into the affected account spot.
newExchanges[i] = newExchanges[newExchanges.length - 1];
// Remove all tokens.
wallets[newExchanges[i]].tokensOwned = 0;
// Set the flag off. No longer an exchange.
wallets[newExchanges[i]].walletIsExchange = false;
// Let it experience taxes and reflections again.
wallets[newExchanges[i]].isExcludedFromTaxAndReflections = false;
// Remove the last entry from the array.
newExchanges.pop();
// Break once found. No need to finish.
break;
}
}
}
}
return;
}
}
| This is a spinoff from the getValues function and it returns the token part of the values Tax is a percentage so we calculate the t value of the fees. transferAmount is tokenAmount minus tax minus liq (to save gas we use the same variable since rate for tax = liq rate) | function getTValues(uint256 tAmount, uint256 tax) private pure returns (uint256, uint256) {
uint256 tFee = tAmount * tax / 10**2;
uint256 tTransferAmount = tAmount - tFee - tFee;
return (tTransferAmount, tFee);
}
| 12,583,428 |
./full_match/4/0x32A2e41B71f523C63af9C87dee0BeE689E6A0D13/sources/zoogame.sol | Interface of the ERC20 standard as defined in the EIP./ | interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
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);
}
| 750,198 |
pragma solidity >=0.8.0 <0.9.0;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ApproveAndCallFallBack.sol";
import "./BancorFormula.sol";
// learn more: https://docs.openzeppelin.com/contracts/3.x/erc20
contract Discover is Ownable, ApproveAndCallFallBack, BancorFormula {
// Could be any MiniMe token
IERC20 sheet;
// Total SHEET in circulation
uint public total;
// Parameter to calculate Max SHEET any one DApp can stake
uint public ceiling;
// The max amount of tokens it is possible to stake, as a percentage of the total in circulation
uint public max;
// Decimal precision for this contract
uint public decimals;
// Prevents overflows in votesMinted
uint public safeMax;
// Whether we need more than an id param to identify arbitrary data must still be discussed.
struct Data {
address developer;
bytes32 id;
bytes32 metadata;
uint balance;
uint rate;
uint available;
uint votesMinted;
uint votesCast;
uint effectiveBalance;
}
Data[] public orientations;
mapping(bytes32 => uint) public id2index;
mapping(bytes32 => bool) public existingIDs;
event OrientationCreated(bytes32 indexed id, uint newEffectiveBalance);
event Upvote(bytes32 indexed id, uint newEffectiveBalance);
event Downvote(bytes32 indexed id, uint newEffectiveBalance);
event Withdraw(bytes32 indexed id, uint newEffectiveBalance);
event MetadataUpdated(bytes32 indexed id);
event CeilingUpdated(uint oldCeiling, uint newCeiling);
constructor(address _SHEET) {
sheet = IERC20(_SHEET);
total = 6942002400;
ceiling = 292; // See here for more: https://observablehq.com/@andytudhope/dapp-store-SNT-curation-mechanism
decimals = 1000000; // 4 decimal points for %, 2 because we only use 1/100th of total in circulation
max = total * ceiling / decimals;
safeMax = uint(77) * max / 100; // Limited by accuracy of BancorFormula
}
/**
* @dev Update ceiling
* @param _newCeiling New ceiling value
*/
function setCeiling(uint _newCeiling) external onlyOwner {
emit CeilingUpdated(ceiling, _newCeiling);
ceiling = _newCeiling;
max = total * ceiling / decimals;
safeMax = uint(77) * max / 100;
}
/**
* @dev Anyone can create an Orientation. You can also restrict it, adding an onlyOwner modifier
* @param _id bytes32 unique identifier.
* @param _amount of tokens to stake on initial ranking.
* @param _metadata metadata hex string
*/
function createOrientation(bytes32 _id, uint _amount, bytes32 _metadata) external {
_createOrientation(
msg.sender,
_id,
_amount,
_metadata);
}
/**
* @dev Sends SHEET directly to the contract, not the developer. This gets added to the DApp's balance, no curve required.
* @param _id bytes32 unique identifier.
* @param _amount of tokens to stake on DApp's ranking. Used for upvoting + staking more.
*/
function upvote(bytes32 _id, uint _amount) external {
_upvote(msg.sender, _id, _amount);
}
/**
* @dev Sends SHEET to the developer and lowers the DApp's effective balance by 1%
* @param _id bytes32 unique identifier.
* @param _amount uint, included for approveAndCallFallBack
*/
function downvote(bytes32 _id, uint _amount) external {
_downvote(msg.sender, _id, _amount);
}
/**
* @dev Developers can withdraw an amount not more than what was available of the
SHEET they originally staked minus what they have already received back in downvotes.
* @param _id bytes32 unique identifier.
* @return max SHEET that can be withdrawn == available SHEET for DApp.
*/
function withdrawMax(bytes32 _id) external view returns(uint) {
Data storage d = _getOrientationById(_id);
return d.available;
}
/**
* @dev Developers can withdraw an amount not more than what was available of the
SHEET they originally staked minus what they have already received back in downvotes.
* @param _id bytes32 unique identifier.
* @param _amount of tokens to withdraw from DApp's overall balance.
*/
function withdraw(bytes32 _id, uint _amount) external {
Data storage d = _getOrientationById(_id);
uint256 tokensQuantity = _amount / (1 ether);
require(msg.sender == d.developer, "Only the developer can withdraw SHEET staked on this data");
require(tokensQuantity <= d.available, "You can only withdraw a percentage of the SHEET staked, less what you have already received");
uint precision;
uint result;
d.balance = d.balance - tokensQuantity;
d.rate = decimals - (d.balance * decimals / max);
d.available = d.balance * d.rate;
(result, precision) = BancorFormula.power(
d.available,
decimals,
uint32(decimals),
uint32(d.rate));
d.votesMinted = result >> precision;
if (d.votesCast > d.votesMinted) {
d.votesCast = d.votesMinted;
}
uint temp1 = d.votesCast * d.rate * d.available;
uint temp2 = d.votesMinted * decimals * decimals;
uint effect = temp1 / temp2;
d.effectiveBalance = d.balance - effect;
require(sheet.transfer(d.developer, _amount), "Transfer failed");
emit Withdraw(_id, d.effectiveBalance);
}
/**
* @dev Set the content for the dapp
* @param _id bytes32 unique identifier.
* @param _metadata metadata info
*/
function setMetadata(bytes32 _id, bytes32 _metadata) external {
uint orientationIdx = id2index[_id];
Data storage d = orientations[orientationIdx];
require(d.developer == msg.sender, "Only the developer can update the metadata");
d.metadata = _metadata;
emit MetadataUpdated(_id);
}
/**
* @dev Get the content for the dapp
* @param _id bytes32 unique identifier.
*/
function getMetadata(bytes32 _id) external view returns(bytes32){
uint orientationIdx = id2index[_id];
Data memory d = orientations[orientationIdx];
return d.metadata;
}
/**
* @dev Used in UI in order to fetch all orientations
* @return orientations count
*/
function getOrientationsCount() external view returns(uint) {
return orientations.length;
}
/**
* @notice Support for "approveAndCall".
* @param _from Who approved.
* @param _amount Amount being approved, needs to be equal `_amount` or `cost`.
* @param _token Token being approved, needs to be `SHEET`.
* @param _data Abi encoded data with selector of `register(bytes32,address,bytes32,bytes32)`.
*/
function receiveApproval (
address _from,
uint256 _amount,
address _token,
bytes calldata _data
)
external override
{
require(_token == address(sheet), "Wrong token");
require(_token == address(msg.sender), "Wrong account");
require(_data.length <= 196, "Incorrect data");
bytes4 sig;
bytes32 id;
uint256 amount;
bytes32 metadata;
(sig, id, amount, metadata) = abiDecodeRegister(_data);
require(_amount == amount, "Wrong amount");
if (sig == bytes4(0x7e38d973)) {
_createOrientation(
_from,
id,
amount,
metadata);
} else if (sig == bytes4(0xac769090)) {
_downvote(_from, id, amount);
} else if (sig == bytes4(0x2b3df690)) {
_upvote(_from, id, amount);
} else {
revert("Wrong method selector");
}
}
/**
* @dev Used in UI to display effect on ranking of user's donation
* @param _id bytes32 unique identifier.
* @param _amount of tokens to stake/"donate" to this DApp's ranking.
* @return effect of donation on DApp's effectiveBalance
*/
function upvoteEffect(bytes32 _id, uint _amount) external view returns(uint effect) {
Data memory d = _getOrientationById(_id);
require(d.balance + _amount <= safeMax, "You cannot upvote by this much, try with a lower amount");
// Special case - no downvotes yet cast
if (d.votesCast == 0) {
return _amount;
}
uint precision;
uint result;
uint mBalance = d.balance + _amount;
uint mRate = decimals - (mBalance * decimals / max);
uint mAvailable = mBalance * mRate;
(result, precision) = BancorFormula.power(
mAvailable,
decimals,
uint32(decimals),
uint32(mRate));
uint mVMinted = result >> precision;
uint temp1 = d.votesCast * mRate * mAvailable;
uint temp2 = mVMinted * decimals * decimals;
uint mEffect = temp1 / temp2;
uint mEBalance = mBalance - mEffect;
return (mEBalance - d.effectiveBalance);
}
/**
* @dev Downvotes always remove 1% of the current ranking.
* @param _id bytes32 unique identifier.
*/
function downvoteCost(bytes32 _id) external view returns(uint b, uint vR, uint c) {
Data memory d = _getOrientationById(_id);
return _downvoteCost(d);
}
function _createOrientation(
address _from,
bytes32 _id,
uint _amount,
bytes32 _metadata
)
internal
{
require(!existingIDs[_id], "You must submit a unique ID");
uint256 tokensQuantity = _amount / (1 ether);
require(tokensQuantity > 0, "You must spend some SHEET to submit a ranking in order to avoid spam");
require (tokensQuantity <= safeMax, "You cannot stake more SHEET than the ceiling dictates");
uint orientationIdx = orientations.length;
Data memory d;
d.developer = _from;
d.id = _id;
d.metadata = _metadata;
uint precision;
uint result;
d.balance = tokensQuantity;
d.rate = decimals - (d.balance * decimals / max);
d.available = d.balance * (d.rate);
(result, precision) = BancorFormula.power(
d.available,
decimals,
uint32(decimals),
uint32(d.rate));
d.votesMinted = result >> precision;
d.votesCast = 0;
d.effectiveBalance = tokensQuantity;
orientations.push(d);
id2index[_id] = orientationIdx;
existingIDs[_id] = true;
require(sheet.transferFrom(_from, address(this), _amount), "Transfer failed");
emit OrientationCreated(_id, d.effectiveBalance);
}
function _upvote(address _from, bytes32 _id, uint _amount) internal {
uint256 tokensQuantity = _amount / (1 ether);
require(tokensQuantity > 0, "You must send some SHEET in order to upvote");
Data storage d = _getOrientationById(_id);
require(d.balance + (tokensQuantity) <= safeMax, "You cannot upvote by this much, try with a lower amount");
uint precision;
uint result;
d.balance = d.balance + (tokensQuantity);
d.rate = decimals - ((d.balance)*(decimals)/(max));
d.available = d.balance * (d.rate);
(result, precision) = BancorFormula.power(
d.available,
decimals,
uint32(decimals),
uint32(d.rate));
d.votesMinted = result >> precision;
uint temp1 = d.votesCast*(d.rate)*(d.available);
uint temp2 = d.votesMinted*(decimals)*(decimals);
uint effect = temp1/(temp2);
d.effectiveBalance = d.balance-(effect);
require(sheet.transferFrom(_from, address(this), _amount), "Transfer failed");
emit Upvote(_id, d.effectiveBalance);
}
function _downvote(address _from, bytes32 _id, uint _amount) internal {
uint256 tokensQuantity = _amount/(1 ether);
Data storage d = _getOrientationById(_id);
(uint b, uint vR, uint c) = _downvoteCost(d);
require(tokensQuantity == c, "Incorrect amount: valid iff effect on ranking is 1%");
d.available = d.available-(tokensQuantity);
d.votesCast = d.votesCast+(vR);
d.effectiveBalance = d.effectiveBalance-(b);
require(sheet.transferFrom(_from, d.developer, _amount), "Transfer failed");
emit Downvote(_id, d.effectiveBalance);
}
function _downvoteCost(Data memory d) internal view returns(uint b, uint vR, uint c) {
uint balanceDownBy = (d.effectiveBalance/(100));
uint votesRequired = (balanceDownBy*(d.votesMinted)*(d.rate))/(d.available);
uint votesAvailable = d.votesMinted-(d.votesCast)-(votesRequired);
uint temp = (d.available/(votesAvailable))*(votesRequired);
uint cost = temp/(decimals);
return (balanceDownBy, votesRequired, cost);
}
/**
* @dev Used internally in order to get a dapp while checking if it exists
*/
function _getOrientationById(bytes32 _id) internal view returns(Data storage d) {
uint orientationIdx = id2index[_id];
d = orientations[orientationIdx];
require(d.id == _id, "Error fetching correct data");
}
/**
* @dev Decodes abi encoded data with selector for "functionName(bytes32,uint256)".
* @param _data Abi encoded data.
*/
function abiDecodeRegister(
bytes memory _data
)
private
pure
returns(
bytes4 sig,
bytes32 id,
uint256 amount,
bytes32 metadata
)
{
assembly {
sig := mload(add(_data, add(0x20, 0)))
id := mload(add(_data, 36))
amount := mload(add(_data, 68))
metadata := mload(add(_data, 100))
}
}
}
| _id bytes32 unique identifier. return max SHEET that can be withdrawn == available SHEET for DApp./ | function withdrawMax(bytes32 _id) external view returns(uint) {
Data storage d = _getOrientationById(_id);
return d.available;
}
| 915,825 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../interfaces/IFantomDeFiTokenStorage.sol";
import "./FantomMintErrorCodes.sol";
// FantomMintCore implements a calculation of different rate steps
// between collateral and debt pools to ensure healthy accounts.
contract FantomMintDebt is Initializable, ReentrancyGuard, FantomMintErrorCodes
{
// define used libs
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20;
// feePool keeps information about the fee collected from token created
// in minted tokens denomination.
// NOTE: No idea what we shall do with the fee pool. Mint and distribute along with rewards maybe?
mapping(address => uint256) public feePool;
// fMintFeeDigitsCorrection represents the value to be used
// to adjust result decimals after applying fee to a value calculation.
uint256 public constant fMintFeeDigitsCorrection = 10000;
// initialize initializes the contract properly before the first use.
function initialize() public initializer {
ReentrancyGuard.initialize();
}
// -------------------------------------------------------------
// Emitted events definition
// -------------------------------------------------------------
// Minted is emitted on confirmed token minting against user's collateral value.
event Minted(address indexed token, address indexed user, uint256 amount, uint256 fee);
// Repaid is emitted on confirmed token repay of user's debt of the token.
event Repaid(address indexed token, address indexed user, uint256 amount);
// -------------------------------------------------------------
// Abstract function required for the collateral manager
// -------------------------------------------------------------
// getFMintFee4dec (abstract) represents the current percentage of the created tokens
// captured as a fee.
// The value is kept in 4 decimals; 50 = 0.005 = 0.5%
function getFMintFee4dec() public view returns (uint256);
// getDebtPool (abstract) returns the address of debt pool.
function getDebtPool() public view returns (IFantomDeFiTokenStorage);
// checkDebtCanIncrease (abstract) checks if the specified
// amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function checkDebtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool);
// getPrice (abstract) returns the price of given ERC20 token using on-chain oracle
// expression of an exchange rate between the token and base denomination.
function getPrice(address _token) public view returns (uint256);
// rewardUpdate (abstract) notifies the reward distribution to update state
// of the given account.
function rewardUpdate(address _account) public;
// canMint checks if the given token can be minted in the fMint protocol.
function canMint(address _token) public view returns (bool);
// getMaxToMint (abstract) calculates the maximum amount of given token
// which will satisfy the given collateral to debt ratio, if added.
function getMaxToMint(address _account, address _token, uint256 _ratio) public view returns (uint256);
// -------------------------------------------------------------
// Debt management functions below, the actual minter work
// -------------------------------------------------------------
// mustMint (wrapper) tries to mint specified amount of tokens
// and reverts on failure.
function mustMint(address _token, uint256 _amount) public nonReentrant {
// make the attempt
uint256 result = _mint(_token, _amount);
// check zero amount condition
require(result != ERR_ZERO_AMOUNT, "non-zero amount expected");
// check low amount condition (fee to amount check)
require(result != ERR_LOW_AMOUNT, "amount too low");
// check minting now enabled for the token condition
require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited");
// check no value condition
require(result != ERR_NO_VALUE, "token has no value");
// check low collateral ratio condition
require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value");
// sanity check for any non-covered condition
require(result == ERR_NO_ERROR, "unexpected failure");
}
// mint allows user to create a specified token against already established
// collateral. The value of the collateral must be in at least configured
// ratio to the total user's debt value on minting.
function mint(address _token, uint256 _amount) public nonReentrant returns (uint256) {
return _mint(_token, _amount);
}
// _mint (internal) does the actual minting of tokens.
function _mint(address _token, uint256 _amount) internal returns (uint256)
{
// make sure a non-zero value is being minted
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// make sure the requested token can be minted
if (!canMint(_token)) {
return ERR_MINTING_PROHIBITED;
}
// what is the value of the borrowed token?
if (0 == getPrice(_token)) {
return ERR_NO_VALUE;
}
// make sure the debt can be increased on the account
if (!checkDebtCanIncrease(msg.sender, _token, _amount)) {
return ERR_LOW_COLLATERAL_RATIO;
}
// calculate the minting fee; the fee is collected from the minted tokens
// adjust the fee by adding +1 to round the fee up and prevent dust manipulations
uint256 fee = _amount.mul(getFMintFee4dec()).div(fMintFeeDigitsCorrection).add(1);
// make sure the fee does not consume the minted amount on dust operations
if (fee >= _amount) {
return ERR_LOW_AMOUNT;
}
// update the reward distribution for the account before the state changes
rewardUpdate(msg.sender);
// add the requested amount to the debt
getDebtPool().add(msg.sender, _token, _amount);
// update the fee pool
feePool[_token] = feePool[_token].add(fee);
// mint the requested balance of the ERC20 token minus the fee
// @NOTE: the fMint contract must have the minter privilege on the ERC20 token!
ERC20Mintable(_token).mint(msg.sender, _amount.sub(fee));
// emit the minter notification event
emit Minted(_token, msg.sender, _amount, fee);
// success
return ERR_NO_ERROR;
}
// mustMintMax tries to increase the debt by maxim allowed amount to stoll satisfy
// the required debt to collateral ratio. It reverts the transaction if the fails.
function mustMintMax(address _token, uint256 _ratio) public nonReentrant {
// try to withdraw max amount of tokens allowed
uint256 result = _mintMax(_token, _ratio);
// check zero amount condition
require(result != ERR_ZERO_AMOUNT, "non-zero amount expected");
// check low amount condition (fee to amount check)
require(result != ERR_LOW_AMOUNT, "amount too low");
// check minting now enabled for the token condition
require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited");
// check no value condition
require(result != ERR_NO_VALUE, "token has no value");
// check low collateral ratio condition
require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value");
// sanity check for any non-covered condition
require(result == ERR_NO_ERROR, "unexpected failure");
}
// mintMax tries to increase the debt by maxim allowed amount to stoll satisfy
// the required debt to collateral ratio.
function mintMax(address _token, uint256 _ratio) public nonReentrant returns (uint256) {
return _mintMax(_token, _ratio);
}
// _mintMax (internal) does the actual minting of tokens. It tries to mint as much
// as possible and still obey the given collateral to debt ratio.
function _mintMax(address _token, uint256 _ratio) internal returns (uint256) {
return _mint(_token, getMaxToMint(msg.sender, _token, _ratio));
}
// mustRepay (wrapper) tries to lower the debt on account by given amount
// and reverts on failure.
function mustRepay(address _token, uint256 _amount) public nonReentrant {
// make the attempt
uint256 result = _repay(_token, _amount);
// check zero amount condition
require(result != ERR_ZERO_AMOUNT, "non-zero amount expected");
// check low balance condition
require(result != ERR_LOW_BALANCE, "insufficient debt outstanding");
// check low allowance condition
require(result != ERR_LOW_ALLOWANCE, "insufficient allowance");
// sanity check for any non-covered condition
require(result == ERR_NO_ERROR, "unexpected failure");
}
// repay allows user to return some of the debt of the specified token
// the repay does not collect any fees and is not validating the user's total
// collateral to debt position.
function repay(address _token, uint256 _amount) public nonReentrant returns (uint256) {
return _repay(_token, _amount);
}
// _repay (internal) does the token burning action.
function _repay(address _token, uint256 _amount) internal returns (uint256)
{
// make sure a non-zero value is being deposited
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// get the pool address
IFantomDeFiTokenStorage pool = getDebtPool();
// make sure there is enough debt on the token specified (if any at all)
if (_amount > pool.balanceOf(msg.sender, _token)) {
return ERR_LOW_BALANCE;
}
// make sure we are allowed to transfer funds from the caller
// to the fMint deposit pool
if (_amount > ERC20(_token).allowance(msg.sender, address(this))) {
return ERR_LOW_ALLOWANCE;
}
// burn the tokens returned by the user first
ERC20Burnable(_token).burnFrom(msg.sender, _amount);
// update the reward distribution for the account before the state changes
rewardUpdate(msg.sender);
// clear the repaid amount from the account debt balance
pool.sub(msg.sender, _token, _amount);
// emit the repay notification
emit Repaid(_token, msg.sender, _amount);
// success
return ERR_NO_ERROR;
}
// mustRepayMax allows user to return as much of the debt of the specified token
// as possible. If the transaction fails, it reverts.
function mustRepayMax(address _token) public nonReentrant {
// try to repay
uint256 result = _repayMax(_token);
// check zero amount condition
require(result != ERR_ZERO_AMOUNT, "non-zero amount expected");
// check low balance condition
require(result != ERR_LOW_BALANCE, "insufficient debt outstanding");
// check low allowance condition
require(result != ERR_LOW_ALLOWANCE, "insufficient allowance");
// sanity check for any non-covered condition
require(result == ERR_NO_ERROR, "unexpected failure");
}
// repayMax allows user to return as much of the debt of the specified token
// as possible.
function repayMax(address _token) public nonReentrant returns (uint256) {
return _repayMax(_token);
}
// _repayMax (internal) reduces the token debt by maximal amount
// possible under the given situation.
// NOTE: Allowance for burning is still required to be high enough
// to allow the operation.
function _repayMax(address _token) internal returns (uint256)
{
// get the debt size, available tokens
uint256 poolBalance = getDebtPool().balanceOf(msg.sender, _token);
uint256 ercBalance = ERC20(_token).balanceOf(msg.sender);
// success
return _repay(_token, Math.min(poolBalance, ercBalance));
}
} | mustMintMax tries to increase the debt by maxim allowed amount to stoll satisfy the required debt to collateral ratio. It reverts the transaction if the fails. try to withdraw max amount of tokens allowed check zero amount condition check low amount condition (fee to amount check) check minting now enabled for the token condition check no value condition check low collateral ratio condition sanity check for any non-covered condition | function mustMintMax(address _token, uint256 _ratio) public nonReentrant {
uint256 result = _mintMax(_token, _ratio);
require(result != ERR_ZERO_AMOUNT, "non-zero amount expected");
require(result != ERR_LOW_AMOUNT, "amount too low");
require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited");
require(result != ERR_NO_VALUE, "token has no value");
require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value");
require(result == ERR_NO_ERROR, "unexpected failure");
}
| 6,391,753 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
// Libraries
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Timers.sol";
import {LibERC721} from "./LibERC721.sol";
// Contracts
import "@openzeppelin/contracts/governance/TimelockController.sol";
library LibGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
enum VoteType {
Against,
For,
Abstain
}
bytes32 internal constant GOVERNOR_STORAGE_POSITION =
keccak256("nffeels.contracts.governor.storage");
bytes32 internal constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,uint8 support)");
uint256 internal constant QUORUM_DENOMINATOR = 100;
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
struct ProposalVote {
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
mapping(address => bool) hasVoted;
}
struct GovernorStorage {
bool init;
string name;
mapping(uint256 => ProposalCore) proposals;
mapping(uint256 => ProposalVote) proposalVotes;
TimelockController timelock;
mapping(uint256 => bytes32) timelockIds;
uint256 quorumNumerator;
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(
address indexed voter,
uint256 proposalId,
uint8 support,
uint256 weight,
string reason
);
/**
* @dev Emitted when the timelock controller used for proposal execution is modified.
*/
event TimelockChange(address oldTimelock, address newTimelock);
/**
* @dev Emitted when the timelock controller used to queue a proposal to the timelock.
*/
event ProposalQueued(uint256 proposalId, uint256 eta);
/**
* @dev Emitted when quorumNumerator is updated from `oldQuoruNumerator` to `newQuorumNumerator`.
*/
event QuorumNumeratorUpdated(
uint256 oldQuoruNumerator,
uint256 newQuorumNumerator
);
function governorStorage()
internal
pure
returns (GovernorStorage storage gs)
{
bytes32 position = GOVERNOR_STORAGE_POSITION;
assembly {
gs.slot := position
}
}
/**
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) internal view returns (uint256) {
return
(LibERC721.getPastTotalSupply(blockNumber) *
governorStorage().quorumNumerator) / QUORUM_DENOMINATOR;
}
/**
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber)
internal
view
returns (uint256)
{
return LibERC721.getPastVotes(account, blockNumber);
}
/**
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal pure returns (uint256) {
return
uint256(
keccak256(
abi.encode(targets, values, calldatas, descriptionHash)
)
);
}
/**
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId) internal view returns (ProposalState) {
ProposalCore memory proposal = governorStorage().proposals[proposalId];
ProposalState status;
if (proposal.executed) {
status = ProposalState.Executed;
} else if (proposal.canceled) {
status = ProposalState.Canceled;
} else if (proposal.voteStart.isPending()) {
status = ProposalState.Pending;
} else if (proposal.voteEnd.isPending()) {
status = ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
status = quorumReached(proposalId) && voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
if (status != ProposalState.Succeeded) {
return status;
}
// Core tracks execution, so we just have to check if successful proposal have been queued.
bytes32 queueid = governorStorage().timelockIds[proposalId];
if (queueid == bytes32(0)) {
return status;
} else if (governorStorage().timelock.isOperationDone(queueid)) {
return ProposalState.Executed;
} else {
return ProposalState.Queued;
}
}
/**
* @dev block number used to retrieve user's votes and quorum.
*/
function proposalSnapshot(uint256 proposalId)
internal
view
returns (uint256)
{
return governorStorage().proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function quorumReached(uint256 proposalId) internal view returns (bool) {
ProposalVote storage proposalvote = governorStorage().proposalVotes[
proposalId
];
return
quorum(proposalSnapshot(proposalId)) <=
proposalvote.forVotes + proposalvote.abstainVotes;
}
/**
* @dev Is the proposal successful or not. In this module, the forVotes must be scritly over the againstVotes.
*/
function voteSucceeded(uint256 proposalId) internal view returns (bool) {
ProposalVote storage proposalvote = governorStorage().proposalVotes[
proposalId
];
return proposalvote.forVotes > proposalvote.againstVotes;
}
/**
* @dev Register a vote with a given support and voting weight. In this module, the support follows the `VoteType` enum (from Governor Bravo).
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal {
ProposalVote storage proposalvote = governorStorage().proposalVotes[
proposalId
];
require(
!proposalvote.hasVoted[account],
"GovernorVotingSimple: vote already cast"
);
proposalvote.hasVoted[account] = true;
if (support == uint8(VoteType.Against)) {
proposalvote.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
proposalvote.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
proposalvote.abstainVotes += weight;
} else {
revert("GovernorVotingSimple: invalid value for enum VoteType");
}
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal {
governorStorage().timelock.executeBatch{value: msg.value}(
targets,
values,
calldatas,
0,
descriptionHash
);
// string memory errorMessage = "Governor: call reverted without message";
// for (uint256 i = 0; i < targets.length; ++i) {
// (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
// Address.verifyCallResult(success, returndata, errorMessage);
// }
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {ProposalCanceled} event.
*/
function cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled &&
status != ProposalState.Expired &&
status != ProposalState.Executed,
"Governor: proposal not active"
);
governorStorage().proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
if (governorStorage().timelockIds[proposalId] != 0) {
governorStorage().timelock.cancel(
governorStorage().timelockIds[proposalId]
);
delete governorStorage().timelockIds[proposalId];
}
return proposalId;
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {getVotes} and call the {_countVote} internal function.
*
* Emits a {VoteCast} event.
*/
function castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal returns (uint256) {
ProposalCore storage proposal = governorStorage().proposals[proposalId];
require(
state(proposalId) == ProposalState.Active,
"Governor: vote not currently active"
);
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/* GovernorTimelockControl */
/**
* @dev Function to queue a proposal to the timelock.
*/
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
require(
state(proposalId) == ProposalState.Succeeded,
"Governor: proposal not successful"
);
uint256 delay = governorStorage().timelock.getMinDelay();
governorStorage().timelockIds[proposalId] = governorStorage()
.timelock
.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
governorStorage().timelock.scheduleBatch(
targets,
values,
calldatas,
0,
descriptionHash,
delay
);
emit ProposalQueued(proposalId, block.timestamp + delay);
return proposalId;
}
/**
* @dev Internal endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
* must be proposed, scheduled and executed using the {Governor} workflow.
*/
function updateTimelock(TimelockController newTimelock) internal {
emit TimelockChange(
address(governorStorage().timelock),
address(newTimelock)
);
governorStorage().timelock = newTimelock;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function executor() internal view returns (address) {
return address(governorStorage().timelock);
}
/* GovernorVotesQuorumFraction */
function updateQuorumNumerator(uint256 newQuorumNumerator) internal {
GovernorStorage storage gs = governorStorage();
require(
newQuorumNumerator <= QUORUM_DENOMINATOR,
"GovernorVotesQuorumFraction: quorumNumerator over QUORUM_DENOMINATOR"
);
uint256 oldQuorumNumerator = gs.quorumNumerator;
gs.quorumNumerator = newQuorumNumerator;
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
}
}
| Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as canceled to allow distinguishing it from executed proposals. Emits a {ProposalCanceled} event./ | function cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled &&
status != ProposalState.Expired &&
status != ProposalState.Executed,
"Governor: proposal not active"
);
governorStorage().proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
if (governorStorage().timelockIds[proposalId] != 0) {
governorStorage().timelock.cancel(
governorStorage().timelockIds[proposalId]
);
delete governorStorage().timelockIds[proposalId];
}
return proposalId;
}
| 12,876,539 |
/**
*Submitted for verification at Etherscan.io on 2022-01-01
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
/**
* @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 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 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;
}
}
/**
* @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 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 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 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 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();
}
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @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 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);
}
}
}
}
/**
* @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 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;
}
}
/**
* @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);
}
}
pragma solidity ^0.8.11;
/**
o
____
| | _____ _ _
| o| | __ \ | | | |
| | | | | | ___ _ __ _ __ | | __ _| |__ ___
|o | | | | |/ _ \ '__| '_ \| | / _` | '_ \/ __|
.' '. | |__| | __/ | | |_) | |___| (_| | |_) \__ \
/ o \ |_____/ \___|_| | .__/|______\__,_|_.__/|___/
:______o___: | |
'.__o_____.' |_| https://derplabs.com
DLV: Dynamic Layered Valuables
**/
contract DerpyLabradors is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
uint256 public constant MAX_SUPPLY = 7500;
uint256 public constant MAX_MINT_AMOUNT = 12;
uint256 private constant DERPLABS_RESERVED = 5;
// ipfs
string public ipfsDir;
string public ipfsGatewayURI = "https://ipfs.derplabs.com/ipfs/";
// mint
bool public mintEnabled;
uint256 public mintFee;
uint256 public mintPromoFee;
// dynamic layer valuable attributes
uint256 public dlvStateCount;
struct DLVToken {
uint256 tokenId;
uint dlvState;
string dlvAlias;
}
// tokenId => dlv attr
mapping (uint256 => DLVToken) private _dlvTokens;
// address => promo redeemed
mapping (address => bool) private _dlvPromoRedeemed;
constructor() ERC721("Derpy Labradors", "DLAB") {
ipfsDir = "QmeDdf7xnubfHSG45X5tCFRgPWhBGqdsZa7cxCjuWEY6iF";
dlvStateCount = 3;
mintFee = 3000000000000000; // .03ETH
mintPromoFee = 1000000000000000; // .01ETH
_tokenIdCounter.increment();
// reserve mint
mintDLV(2, DERPLABS_RESERVED);
}
function mintDLV(uint stateId, uint amount) public payable {
require(mintEnabled || msg.sender == owner(), "Minting disabled, sale is either paused or concluded");
require(stateId <= (dlvStateCount - 1) && stateId >= 0, "Invalid state value");
require(amount > 0, "Amount requested must be 1 or greater");
require(amount <= MAX_MINT_AMOUNT || msg.sender == owner(), "Amount requested exceeds limit");
require((totalSupply() + amount) <= MAX_SUPPLY, "Amount requested exceeds max supply available");
require((mintFee * amount) <= msg.value || msg.sender == owner(), "ETH value sent does not match mint price");
uint256 tokenId = _tokenIdCounter.current();
for (uint i = 1; i < amount + 1; i++) {
_safeMint(msg.sender, tokenId);
_tokenIdCounter.increment();
// initialize dlv token, mapping attribute dir to tokenId
_dlvTokens[tokenId] = DLVToken(tokenId, stateId, string(abi.encodePacked("#", uint2str(tokenId))));
tokenId = _tokenIdCounter.current();
}
}
function promoMintDLV(uint stateId) public payable returns (uint256) {
require(mintEnabled || msg.sender == owner(), "Minting disabled, sale is either paused or concluded");
require(stateId <= (dlvStateCount - 1) && stateId >= 0, "Invalid state value");
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= MAX_SUPPLY, "Max supply reached");
require(_dlvPromoRedeemed[msg.sender] == false, "Promotional mint already redeemed");
require(mintPromoFee <= msg.value || msg.sender == owner(), "ETH value sent does not match mint price");
_safeMint(msg.sender, tokenId);
_tokenIdCounter.increment();
_dlvPromoRedeemed[msg.sender] = true;
// initialize dlv token, mapping attribute dir to tokenId
_dlvTokens[tokenId] = DLVToken(tokenId, stateId, string(abi.encodePacked("#", uint2str(tokenId))));
return tokenId;
}
function enableMint(bool isEnabled) external onlyOwner() {
mintEnabled = isEnabled;
}
function resetWalletPromo(address addr) external onlyOwner() {
_dlvPromoRedeemed[addr] = false;
}
function setIPFSDir(string memory dir) external onlyOwner() {
ipfsDir = dir;
}
function setMintFee(uint256 fee) external onlyOwner() {
mintFee = fee;
}
function setMintPromoFee(uint256 fee) external onlyOwner() {
mintPromoFee = fee;
}
function setStateCount(uint count) external onlyOwner() {
dlvStateCount = count;
}
function setAlias(uint256 tokenId, string memory name) external {
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "Sender is not token owner or contract owner");
require(bytes(name).length <= 15, "Name Length must not exceed 15 chars");
_dlvTokens[tokenId].dlvAlias = name;
}
function setBaseURI(string memory uri) external onlyOwner() {
ipfsGatewayURI = uri;
}
function setDLVState(uint256 tokenId, uint stateId) external {
require(_exists(tokenId), "ERC721Metadata: nonexistent token");
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "Sender is not token owner or contract owner");
require(stateId <= (dlvStateCount - 1) && stateId >= 0, "Invalid state value");
_dlvTokens[tokenId].dlvState = stateId;
}
function _baseURI() internal view virtual override returns (string memory) {
return ipfsGatewayURI;
}
function getAlias(uint256 tokenId) external view virtual returns (string memory) {
return string(_dlvTokens[tokenId].dlvAlias);
}
function promoRedeemed(address addr) external view virtual returns (bool) {
return _dlvPromoRedeemed[addr];
}
function dlvState(uint256 tokenId) external view virtual returns (uint) {
require(_exists(tokenId), "ERC721Metadata: nonexistent token");
return _dlvTokens[tokenId].dlvState;
}
function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: nonexistent token");
string memory base = _baseURI();
uint stateId = _dlvTokens[tokenId].dlvState;
return string(abi.encodePacked(base, ipfsDir, "/", uint2str(tokenId), ".", uint2str(stateId), ".json"));
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
// reset alias
_dlvTokens[tokenId].dlvAlias = string(abi.encodePacked("#", uint2str(tokenId)));
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// withdraw the things
function withdrawContractETH() external onlyOwner() {
payable(address(msg.sender)).transfer(address(this).balance);
}
function withdrawAmountContractETH(uint256 amount) external onlyOwner() {
payable(address(msg.sender)).transfer(amount);
}
// helpers
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
} | initialize dlv token, mapping attribute dir to tokenId | function mintDLV(uint stateId, uint amount) public payable {
require(mintEnabled || msg.sender == owner(), "Minting disabled, sale is either paused or concluded");
require(stateId <= (dlvStateCount - 1) && stateId >= 0, "Invalid state value");
require(amount > 0, "Amount requested must be 1 or greater");
require(amount <= MAX_MINT_AMOUNT || msg.sender == owner(), "Amount requested exceeds limit");
require((totalSupply() + amount) <= MAX_SUPPLY, "Amount requested exceeds max supply available");
require((mintFee * amount) <= msg.value || msg.sender == owner(), "ETH value sent does not match mint price");
uint256 tokenId = _tokenIdCounter.current();
for (uint i = 1; i < amount + 1; i++) {
_safeMint(msg.sender, tokenId);
_tokenIdCounter.increment();
_dlvTokens[tokenId] = DLVToken(tokenId, stateId, string(abi.encodePacked("#", uint2str(tokenId))));
tokenId = _tokenIdCounter.current();
}
}
| 15,253,492 |
./partial_match/4/0x8915F3d8Dd4954788041671CB57Be0BE3f0C47a2/sources/SQUIDMASTER.sol | Withdraw LP tokens from SQUIDMASTER._pid 0 Stake pool | 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.accSquidPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeSquidTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
if(_pid == 0){
_totalSquidStaked = _totalSquidStaked.sub(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSquidPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,509,428 |
./full_match/42/0x0Fe06cD3C414fc3626da3fD6D330f61d24080f3D/sources/docs.chain.link/samples/Roulette.sol | $50 minimumrequire(msg.value >= getEntranceFee(), "Not enough ETH!"); | function enter(uint256[] memory _bet) public payable {
require(roulette_state == LOTTERY_STATE.OPEN);
if (playerToBet[payable(msg.sender)].length == 0) {
players.push(payable(msg.sender));
}
playerToBet[msg.sender].push(Bet(_bet, msg.value));
}
| 16,253,498 |
./partial_match/1/0xb91371Eeb9f2D2A690429FB2F4Ee84a718C4dA0c/sources/BigMoney.sol | If the tokens were bought less than 15 days ago and the sender is not exempt, reject the transaction If the tokens are being transferred to a new address, record the purchase time Note that the purchase time won't be updated for exempt addresses | function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
if (!isExempt[sender] && block.timestamp < purchaseTime[sender] + 15 days) {
revert("BIG$: Tokens are locked for the first 15 days after purchase");
}
if (purchaseTime[recipient] == 0 && !isExempt[recipient]) {
purchaseTime[recipient] = block.timestamp;
}
super._transfer(sender, recipient, amount);
}
| 4,116,748 |
./partial_match/1/0x28e55c21A97FD6fb4A19fA146aF5C359791E86bC/sources/PepeApe.sol | Sets if the contract can sell tokens enabled set to false to disable selling | function setCanSwapback(bool enabled) external onlyOwner {
swapbackOn = enabled;
}
| 11,012,063 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.